Spring-cloud学习笔记— Hystrix介绍
1. Hystrix简介
Hystrix
(豪猪----->刺),宣⾔“defend your app”(保护你的APP),是由Netflix开源的⼀个延迟和容错库,⽤于隔离访问远程系统、服务或者第三⽅库,防⽌级联失败,从⽽提升系统的可⽤性与容错性。Hystrix
主要通过以下⼏点实现延迟和容错。包裹请求
:使⽤HystrixCommand
包裹对依赖的调⽤逻辑。 ⾃动投递微服务⽅法,先假设调⽤某个微服务(在调用方使用注解@HystrixCommand
添加Hystrix控制,其实是对注解进行切面编程)跳闸机制
:当某服务的错误率超过⼀定的阈值时,Hystrix可以跳闸,停⽌请求该服务⼀段时间。资源隔离
:Hystrix为每个依赖都维护了⼀个⼩型的线程池(舱壁模式)(或者信号量)
。如果该线程池已满, 发往该依赖的请求就被⽴即拒绝,⽽不是排队等待,从⽽加速失败判定。监控
:Hystrix可以近乎实时地监控运⾏指标和配置的变化,例如:成功、失败、超时、以及被拒绝的请求等。回退机制
:当请求失败、超时、被拒绝,或当断路器打开时,执⾏回退逻辑。回退逻辑由开发⼈员⾃⾏提供,例如返回⼀个缺省值。⾃我修复
:断路器打开⼀段时间后,会⾃动进⼊“半开”状态。
2. Hystrix熔断应用
-
应用思路简介
-
引入jar包
<!--熔断器Hystrix--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
-
打开
Hytrix
功能:在springboot启动类上使用注解@EnableHystrix
:开启Hystrix的功能@EnableCircuitBreaker
:开启熔断器功能- 以上两个注解选择一个就好,一般用第二个
- 注解简化方法:
@SpringCloudApplication
=@SpringBootApplication
+@EnableDiscoveryClient
+@EnableCircuitBreaker
代码样例
:@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class AutodeliverApplication { SpringApplication.run(AutodeliverApplication.class, args); }
-
Hystrix
熔断实例:调用其他服务超时或者因为其他原因调用失败,直接熔断,断开调用@HystrixCommand( // commandProperties熔断的⼀些细节属性配置,大括号里面是属性配置 commandProperties = { // 每⼀个属性都是⼀个HystrixProperty, // 里面的属性都在HystrixCommandProperties里面定义了很多的属性 @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="2000") } ) @GetMapping("/checkStateTimeout/{userId2}") public Integer findResumeOpenStateTimeOut(@PathVariable("userId2")Long userId){ //调用远程服务--->调用简历微服务,使用RestTemplate String url = "http://localhost:8080/resume/openstate/"; Integer forObject = restTemplate.getForObject(url + userId, Integer.class); return forObject; }
-
Hystrix
降级实例:- 服务提供者处理超时,熔断,返回错误信息
- 有可能服务提供者出现异常直接抛出异常信息
- 以上信息,都会返回到消费者这⾥,很多时候消费者服务不希望把收到异常/错误信息再抛到它的上游去
- 比如:⽤户微服务 — 注册微服务 — 优惠券微服务
- 登记注册
- 分发优惠券(并不是核⼼步骤),这⾥如果调⽤优惠券微服务返回了异常信息或者是熔断后的错误信息,这些信息如果抛给⽤户很不友好
- 此时,我们可以返回⼀个兜底数据,预设的默认值(服务降级)
/** * 模拟超时,调用方法添加Hystrix控制 * 使⽤@HystrixCommand注解进⾏熔断控制,配置fallback回调函数,设置降级 */ @HystrixCommand( // commandProperties熔断的⼀些细节属性配置,大括号里面是属性配置 commandProperties = { // 每⼀个属性都是⼀个HystrixProperty, // 里面的属性都在HystrixCommandProperties里面定义了很多的属性 @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="2000") }, //回退方法 fallbackMethod = "myFallback" ) @GetMapping("/checkStateTimeoutFallback/{userId}") public Integer findResumeOpenStateTimeOutFallback(@PathVariable("userId")Long userId){ //调用远程服务--->调用简历微服务,使用RestTemplate String url = "http://localhost:8080/resume/openstate/"; Integer forObject = restTemplate.getForObject(url + userId, Integer.class); return forObject; } /** * 定义回退方法,返回预设默认值 * 注意:该方法的形参和返回值与原方法保持一致 */ public Integer myFallback(Long userId){ //设置的兜底数据 return -1; }