Hystrix 扇出 雪崩 较低级别的服务中的服务故障可能导致用户级联故障。当对特定服务的呼叫达到一定阈值时(Hystrix中的默认值为5秒内的20次故障), Hystrix能够保证在一个依赖故障的情况下,不会导致整体服务失败,避免级联故障,提高分布式系统的弹性 当某个服务故障之后,通过断路器的故障监控,向调用方返回一个符合预期的、可处理的响应(fallback),而不是长时间的等待或者抛出方法无法处理的异常,保证服务调用方的线程不会被长时间、不必要的占用,避免了故障在系统中蔓延,乃至雪崩 服务故障或者异常,当某个异常条件被触发,直接熔断整个服务,而不是一直等到此服务超时
服务降级是在客户端完成的,与服务端无关 当服务被熔断后,服务将不再被调用,客户端准备一个fallback的回调,返回缺省值
1. Ribbon+Hystrix
- 使用Consumer9001项目改造,pom中引入依赖文件
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 配置熔断方法
com.xyz.controller.ConsumerDeptController
@RequestMapping("/consumer/list")
@HystrixCommand(fallbackMethod = "consumerFallback")
public Dept list() {
return restTemplate.getForObject(REST_URL_PREFIX + "/provider/list", Dept.class);
}
public Dept consumerFallback() {
return new Dept().setDeptNo(9001)
.setDeptName("ribbon-hystrix-name-9001")
.setDeptDesc("ribbon-hystrix-desc-9001");
}
- 主启动类开启对Hystrix的支持
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class Consumer9001 {
public static void main(String[] args) {
SpringApplication.run(Consumer9001.class, args);
}
}
- 启动注册中心7001、consumer9001,访问
http://localhost:9001/consumer/list
2. Feign+Hystrix
- 修改com.xyz.service.DeptService接口,支持fallback
@FeignClient(value = "microservice-provider", fallbackFactory = DeptServcieFallBackFactory.class) @Service public interface DeptService { @RequestMapping("/provider/list") Dept list(); } - 增加fallbackfactory类com.xyz.fallback.DeptServcieFallBackFactory
@Component public class DeptServcieFallBackFactory implements FallbackFactory<DeptService> { @Override public DeptService create(Throwable throwable) { return new DeptService() { @Override public Dept list() { return new Dept().setDeptNo(9999) .setDeptName("fallbackfactory_name") .setDeptDesc("fackbackfacotry_desc"); } }; } } - 修改consumerFeign-9101项目,在feign中开启hystrix
#在Feign中开发Hystrix feign: hystrix: enabled: true - 启动注册中心7001、ConsumerFeign9101,验证
http://localhost:9101/consumerfeign/list
代码示例-github
参考
- Spring Cloud构建微服务架构:服务容错保护(Hystrix服务降级)【Dalston版】-程序猿DD
- Spring Cloud构建微服务架构:服务容错保护(Hystrix依赖隔离)【Dalston版】-程序猿DD
- Spring Cloud构建微服务架构:服务容错保护(Hystrix断路器)【Dalston版】-程序猿DD
- Spring Cloud构建微服务架构:Hystrix监控面板【Dalston版】-程序猿DD
- Spring Cloud构建微服务架构:Hystrix监控数据聚合【Dalston版】-程序猿DD
- springcloud(四):熔断器Hystrix-纯洁的微笑
- springcloud(五):熔断监控Hystrix Dashboard和Turbine-纯洁的微笑
- Hystrix的用处、解决的问题、工作流程图、断路器流程