【SpringCloud Greenwich版本】第五章:断路器(hystrix)

一、SpringCloud版本

本文介绍的Springboot版本为2.1.1.RELEASE,SpringCloud版本为Greenwich.RC1,JDK版本为1.8,集成环境为IntelliJ IDEA

二、hystrix介绍

Netflix的创造了一个调用的库Hystrix实现了断路器图案。在微服务架构中,通常有多层服务调用。
在这里插入图片描述
较低级别的服务中的服务故障可能导致用户级联故障。当对特定服务的呼叫达到一定阈值时(Hystrix中的默认值为5秒内的20次故障),电路打开,不进行通话。在错误和开路的情况下,开发人员可以提供后备。
在这里插入图片描述
开放式电路会停止级联故障,并允许不必要的或失败的服务时间来愈合。回退可以是另一个Hystrix保护的调用,静态数据或一个正常的空值。回退可能被链接,所以第一个回退使得一些其他业务电话又回到静态数据。

三、创建hystrix服务

  • 3.1创建

由于Springboot2.1.1 Feign 已经集成了hystrix服务,所以我们只需简单的改造cloudcustomer工程即可。

首先,根据前文启动cloudser和两个cloudclient服务,cloudclient服务端口分别为8002,8003,然后再修改cloudcustomer工程中的接口方法,在@FeignClient注解中增加fallback = SchedualServiceHiHystric.class
fallback 代表返回操作

package com.jthao.cloudcustomer.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "cloudclient", fallback = SchedualServiceHiHystric.class)
public interface TestService {
    @RequestMapping("/test")
    String hello(@RequestParam String name);
}

定义SchedualServiceHiHystric断路器返回保护操作,在这里我们简单的设置一段返回信息

package com.jthao.cloudcustomer.service;

import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements TestService {
    @Override
    public String hello(String name) {
        return "sorry " + name;
    }
}
  • 3.2启动

启动类中保持不变,@EnableDiscoveryClient服务注册和@EnableFeignClients服务消费

package com.jthao.cloudcustomer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class CloudcustomerApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudcustomerApplication.class, args);
    }

}

Feign默认为开启hystrix服务,各个不同版本可能不一致,所以为了保险起见,在配置文件中开启hystrix服务,其中feign.hystrix.enabled=true代表hystrix服务开启,false关闭hystrix服务

eureka.client.service-url.defaultZone: http://localhost:8001/eureka/
server.port=8004
spring.application.name=cloudcustomer
feign.hystrix.enabled=true
  • 3.3访问

通过浏览器多次访问http://localhost:8004/test?name=honghong,我们可以看到如下展示

honghong===端口:8002被调用了===
honghong===端口:8003被调用了===

这时我们关闭端口为8003的cloudclient服务,再次访问http://localhost:8004/test?name=honghong,可以看到如下展示

honghong===端口:8002被调用了===
sorry honghong

至此断路器已经启作用了

猜你喜欢

转载自blog.csdn.net/haobao528/article/details/85276432
今日推荐