前言:
在分布式架构中,当某个服务单元发生故障,通过断路器的故障监控,向调用方返回一个错误响应,而不是长时间的等待。这样就不会使得线程因调用故障服务被长时间占用不释放,避免了故障在分布式系统中的蔓延。
针对上述问题,Spring Clound Hystrix 实现了断路器、线程隔离等一系列的服务保护的功能。
具体实现如下。
(一)添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
(二)添加注解
@EnableCircuitBreaker
注意(@SpringBootApplication + @EnableFeignClients + @EnableCircuitBreaker = @SpringCloudApplication)
(三)整合hystrix的具体代码实现
I.使用RestTemplat作为服务间通信的整合方式
正常情况下
如果停掉product的服务
这就是熔断器的效果
当需要降级的接口很多的时候,如果对每一个都进行配置就很繁琐
可以通过如下方式
对需要降级的接口加上@HystrixCommand注解即可完成默认降级
效果如下
关于Hystrix的一些特别用法
用法1
令目标服务等待2S后返回结果
改超时时间为3s
用时2S成功获取到商品信息
用法2
注释掉这段配置,这样就一定会触发降级
然后代码改动如下
当number=1时,会返回成功,否则会触发降级
如果一直入参传number!=1,则一直降级,降级之后的下一次传入参number=1
会发现还是返回降级
这是由于触发了断路器,对服务进行了保护。
查看源码可以看到,断路器是默认启用的。
再看这几个默认配置
意思是每20个请求,如果有50%以上的请求被降级,那么此时会进入休眠时间窗5S,在这期间,应用再次接收到该请求会直接进入降级。5S之后如果下一次请求依然失败,则会再次进入休眠时间窗。
这些参数都是可以自行配置的,配置方法与之间的超时时间相似
这里不再过多的讲述了。
II.使用Feign作为服务通信时整合Hystrix
配置application.yml文件需要加上以下内容
feign:
hystrix:
enabled: true
接口代码:
@GetMapping("getOrder")
public String getOrder(){
String respons=productClient.getProductMsg();
return respons;
}
关于配置fallBack的方法
@FeignClient(name ="product" , fallback = ProductClient.ProductClientFallBack.class)
public interface ProductClient {
@GetMapping("/productMsg")
String getProductMsg();
@Component
static class ProductClientFallBack implements ProductClient{
@Override
public String getProductMsg() {
return "feign:熔断了";
}
}
}
效果如下
可以看出代码非常简洁清晰
所以个人更喜欢通过Feign作为服务间通信的方式。
(四)Hystrix-dashboard
该组件是专门用来监听熔断器的工具
1.首先加入如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.启动类加上注解
@EnableHystrixDashboard
3.配置文件加入以下内容
management:
endpoints:
web:
exposure:
include: hystrix.stream
4.访问hystrix可以查看监控信息