文章目录
- 提前预知
- 10、Hystrix熔断器
- 10.1、Hystrix是什么
- 10.2、Hystrix停更进维
- 10.3、Hystrix的服务降级熔断限流概念
- 10.4、Hystrix支付微服务构建
- 10.5、JMeter高并发压测后卡顿
- 10.6、订单微服务调用支付服务出现卡顿
- 10.7、降级容错解决的维度要求
- 10.8、Hystrix服务降级之支付侧降级(fallback)
- 10.9、Hystrix服务降级之订单侧降级(fallback)
- 10.10、Hystrix服务降级之全局服务降级DefaultProperties
- 10.11、Hystrix之通配服务降级FeignFallback
- 10.12、Hystrix之服务熔断理论
- 10.13、Hystrix之服务熔断案例
- 10.14、Hystrix之服务熔断总结
- 10.15、Hystrix工作流程最后总结
- 10.16、Hystrix图形化Dashboard搭建
- 10.17、 Hystrix图形化Dashboard监控实战
提前预知
学习一种技术最好的方式是:视屏+官方文档!!!!!
官网文档地址:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/
注意:这个是H版的SR1对应的文档,如果想看其他版本的直接更改链接中的版本号即可,例如查看Hoxton.SR2版本,如下:
https://cloud.spring.io/spring-cloud-static/Hoxton.SR2/reference/htmlsingle/
代码地址:https://gitee.com/aismall/spring-cloud
windows中端口被占用的处理方式:
查看端口号被那个应用占用:netstat -ano |findstr "端口号"
通过进程id查找对应的进程名称:tasklist |findstr "进程id号"
根据进程或id名称杀掉进程:taskkill /f /t /im "进程id或者进程名称"
本次笔记对应的课程为尚硅谷的Springcloud教程,课程地址:springcloud课程地址
课程包含:springcloud
+springcloud alibaba
课程分为四个等级(不一定要一次性学完,你懂得!!!):
- 零:1~4
- 初:5~9
- 中:10~16
- 高:17~21
课程大纲:
一点一点的学习下面这些组件!!!!!
10、Hystrix熔断器
10.1、Hystrix是什么
分布式系统面临的问题
- 复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地会失败。
服务雪崩
-
多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的
扇出
。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,这就是所谓的雪崩效应
-
对于高流量的应用来说,
单一的后端
依赖可能会导致所有服务器上的所有资源都在几秒钟内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障
。这些都表示需要对故障和延迟
进行隔离和管理,以便单个依赖关系的失败,不能殃及个应用程序或系统
。 -
所以,通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫
雪崩
。
Hystrix是什么
-
Hystrix是一个用于处理分布式系统的
延迟和容错
的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性
。 -
断路器
本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应
(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。
Hystrix能干嘛
- 服务降级
- 服务熔断
- 接近实对的监控
- …
10.2、Hystrix停更进维
官网资料链接:https://github.com/Netflix/Hystrix/wiki/How-To-Use
Hystrix官宣,停更进维:https://github.com/Netflix/Hystrix
注意:官网推荐使用resilience4j
,但是国内使用的比较少,一般都是用Spring Cloud Alibaba的Sentinel
因为Hystrix这个熔断器的设计思想很牛,后面的熔断器的设计思想也都是参考这个,所以还是有必要学习一下的。
10.3、Hystrix的服务降级熔断限流概念
注意:服务降级(fallback),服务熔断(break),服务限流(flowlimit)不是一个概念
服务降级:
-
服务器忙,请稍后再试,不让客户端等待并立刻返回一个友好提示,fallback
-
哪些情况会出发降级
- 程序运行导常 - 超时 - 服务熔断触发服务降级 - 线程池/信号量打满也会导致服务降级
服务熔断
-
类比保险丝达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示。
-
服务的降级 -> 进而熔断 -> 恢复调用链路
服务限流
- 秒杀高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟N个,有序进行。
10.4、Hystrix支付微服务构建
前面我们的7001和7002
类似于一个集群,每次都两个一起启动,太麻烦,我们创建一个7003
的单机版的Eureka节点,参考cloud-eureka-server7001
的创建方式,创建一个单机版的cloud-eureka-server7003
注意:在本机的host文件
添加如下代码:
127.0.0.1 eureka7003.com
下面我们要创建一个带Hystrix的支付实例:
1、新建cloud-provider-hystrixpayment8001
2、POM
<dependencies>
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>com.aismall</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、YML
server:
port: 8001
spring:
application:
name: cloud-provider-hystrix-payment
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
#defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
defaultZone: http://eureka7003.com:7003/eureka
4、主启动
@SpringBootApplication
@EnableEurekaClient
public class PaymentHystrixMain8001
{
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
}
5、业务类
- service
/*
* 注意:这里仅做演示,没有从数据库中取数据,直接返回的字符串值
* */
@Service
public class PaymentService {
public String paymentInfo_OK(Integer id) {
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_OK,id: "+id+"\t"+"O(∩_∩)O哈哈~";
}
public String paymentInfo_TimeOut(Integer id) {
try { TimeUnit.MILLISECONDS.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
return "线程池: "+Thread.currentThread().getName()+" id: "+id+"\t"+"O(∩_∩)O哈哈~"+" 耗时(秒): 3";
}
}
- controller
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id) {
//调用service中放入方法,返回一个字符串
String result = paymentService.paymentInfo_OK(id);
//打印log到控制台
log.info("*****result: "+result);
//将这个字符串返回到客户端
return result;
}
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
String result = paymentService.paymentInfo_TimeOut(id);
log.info("*****result: "+result);
return result;
}
}
6.正常测试
- 启动eureka7003
- 启动cloud-provider-hystrix-payment8001
- 浏览器访问:http://localhost:8001/payment/hystrix/ok/1
- 每次调用耗费5秒钟:http://localhost:8001/payment/hystrix/timeout/1
- 上面的测试均没有问题,我们以上面的为根基,进行后续演示:从
正确 -> 错误 -> 降级熔断 -> 恢复
。
10.5、JMeter高并发压测后卡顿
上面的情况在非高并发情形下,还能勉强满足,我们下面进行压力测试。
使用JMeter这个工具进行压测:
使用
20000
个并发量来访问那个带延时的端口:http://localhost:8001/payment/hystrix/timeout/1
JMeter官方下载网站:https://jmeter.apache.org/download_jmeter.cgi
其他版本下载地址:https://archive.apache.org/dist/jmeter/binaries/
启动方式:
使用方式:
当我们进行压力的测试的时候,使用浏览器去访问那个没有延时的链接
的时候,也会出现卡顿
的情况,拖慢了该服务中的其他线程
。
- 浏览器访问:
http://localhost:8001/payment/hystrix/ok/1
10.6、订单微服务调用支付服务出现卡顿
我们在新建一个消费服务
,使用这个消费服务去调用这个支付服务(8001)!!!!
当我们使用消费服务调用支付服务(8001)的时候,同时对支付服务(8001)进行压测,此时消费服务也会出现延时现象,这是必然的。
1、新建 :cloud-consumer-feign-hystrix-order80
2.POM
<dependencies>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.aismall</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--一般基础通用配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、YML
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7003.com:7003/eureka/
4、主启动
@SpringBootApplication
@EnableFeignClients
//@EnableHystrix
public class OrderHystrixMain80 {
public static void main(String[] args)
{
SpringApplication.run(OrderHystrixMain80.class,args);
}
}
5、业务类
- service
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" /*,fallback = PaymentFallbackService.class*/)
public interface PaymentHystrixService
{
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
- controller
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" /*,fallback = PaymentFallbackService.class*/)
public interface PaymentHystrixService
{
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
6、正常测试,开启cloud-eureka-server7003
,cloud-provider-hystrixpayment8001
,cloud-consumer-feign-hystrixorder80
三个微服务。
- 浏览器访问:
http://localhost/consumer/payment/hystrix/ok/1
7、高并发测试
-
打开压力测试:2W个线程压8001(
前面已经做过
) -
浏览器访问:
http://localhost/consumer/payment/hystrix/ok/32
-
结果:消费者80被拖慢
-
原因:8001同一层次的其它接口服务被困死,因为tomcat线程池里面的工作线程已经被挤占完毕。
正因为有上述故障或不佳表现才有我们的降级/容错/限流等技术诞生。
10.7、降级容错解决的维度要求
超时导致服务器变慢(转圈) :超时不再等待
出错(宕机或程序运行出错) :出错要有兜底
解决方案:
- 对方服务(8001)超时了,调用者(80)不能一直卡死等待,必须有服务降级。
- 对方服务(8001)宕机了,调用者(80)不能一直卡死等待,必须有服务降级。
- 对方服务(8001)OK,调用者(80)自己出故障或有自我要求(自己的等待时间小于服务提供者),自己处理降级。
10.8、Hystrix服务降级之支付侧降级(fallback)
降级配置使用这个注解:@HystrixCommand
先处理这个支侧的降级:cloud-provider-hystrixpayment8001
设置自身调用超时时间的峰值
,峰值内可以正常运行
,超过了需要有兜底的方法处理,作服务降级fallback
。
设置方式:
-
第一步:对支付服务中提供服务的方法进行
改写
,如下:@Service public class PaymentService{ // 在这个方法上标注注解,如果这个方法挂了,就用注解中的方法兜底 // 在commandProperties 设置容忍的超时时间是3秒钟 @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler"/*指定善后方法名*/,commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000") }) public String paymentInfo_TimeOut(Integer id){ //第二种:计算异常 //int age = 10/0; // 第一种:设置延时时间是5秒,这样就会走兜底的方法 try { TimeUnit.MILLISECONDS.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return "线程池: "+Thread.currentThread().getName()+" id: "+id+"\t"+"O(∩_∩)O哈哈~"+" 耗时(秒): "; } //用来兜底的方法 public String paymentInfo_TimeOutHandler(Integer id){ return "线程池: "+Thread.currentThread().getName()+" 8001系统繁忙或者运行报错,请稍后再试,id: "+id+"\t"+"o(╥﹏╥)o"; } }
—旦调用服务方法失败并抛出了错误信息后,会自动调用
@HystrixCommand
标注好的fallbackMethod指定的方法 -
第二步:在服务主启动类中添加新注解
@EnableCircuitBreaker
@SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker//添加到此处 public class PaymentHystrixMain8001{ public static void main(String[] args) { SpringApplication.run(PaymentHystrixMain8001.class, args); } }
异常演示:
- 第一种
:延时异常
,我们能接受3秒钟,它运行5秒钟,超时异常。 - 第二种:
运行异常
,int age = 10/0
开始测试,开启cloud-eureka-server7003
,cloud-provider-hystrixpayment8001
,cloud-consumer-feign-hystrixorder80
三个微服务。
- 浏览器访问:
http://localhost:8001/payment/hystrix/timeout/1
10.9、Hystrix服务降级之订单侧降级(fallback)
再处理这个消费侧的降级:cloud-consumer-feign-hystrixorder80
如法炮制
- 修改YML
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
#开启
feign:
hystrix:
enabled: true
修改主启动:添加@EnableHystrix
注解
@SpringBootApplication
@EnableFeignClients
@EnableHystrix//添加到此处
public class OrderHystrixMain80{
public static void main(String[] args){
SpringApplication.run(OrderHystrixMain80.class,args);
}
}
修改业务类controller
:
@RestController
@Slf4j
public class OrderHystirxController {
@Resource
private PaymentHystrixService paymentHystrixService;
// 添加注解
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")
})
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
//int age = 10/0;
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
//由于兜底的方法
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){
return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
}
}
开始测试,开启cloud-eureka-server7003
,cloud-provider-hystrixpayment8001
,cloud-consumer-feign-hystrixorder80
三个微服务。
- 浏览器访问:
http://localhost/consumer/payment/hystrix/timeout/1
10.10、Hystrix服务降级之全局服务降级DefaultProperties
前面的对于每个方法都做降级处理固然好,但是也会有问题
:每个业务方法对应一个兜底的方法,代码膨胀
如何解决方法
- 对于特殊的方法的降级处理采用上面的那种一对一的降级处理。
- 对于一般的方法的降级处理采用一对多的降级处理
如何实现:
-
我们对于一对多的降级处理采用
@DefaultProperties(defaultFallback = " ")
统一跳转到统一处理结果页面 -
将通用的和独享的各自分开,避免了代码膨胀,合理减少了代码量。
处理顺序:
- 当被调用方法发生异常,如果
方法上标明了降级处理对应的方法
(一对一的那种),就优先调用本方法指定的降级处理方式,否则就去找全局通用降级处理方式
。 - 也就是:一对一大于一对多
- 注意:
@DefaultProperties
注解标在类上,@HystrixCommand
标在方法上。
代码实现:
@RestController
@Slf4j
// 指定全局降级处理方法
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystirxController {
@Resource
private PaymentHystrixService paymentHystrixService;
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id)
{
String result = paymentHystrixService.paymentInfo_OK(id);
return result;
}
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
//用全局的fallback方法,注意:如果想要降级一定要标这个注解
// 注解中不指定方法,就会去找全局降级处理方法
@HystrixCommand
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
//int age = 10/0;
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
// 一对一的兜底方法
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){
return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
}
// 全局兜底方法,一对多
public String payment_Global_FallbackMethod(){
return "Global异常处理信息,请稍后再试,/(ㄒoㄒ)/~~";
}
}
开始测试,开启cloud-eureka-server7003
,cloud-provider-hystrixpayment8001
,cloud-consumer-feign-hystrixorder80
三个微服务。
- 浏览器访问:
http://localhost/consumer/payment/hystrix/timeout/1
10.11、Hystrix之通配服务降级FeignFallback
前面的全局降级处理是最好的吗?还有需要优化的地方吗?
存在的问题:业务代码和降级代码放在一起,比较混乱
!!!!我们将其分开!!!!
吐槽一下:
WTM FC
服务降级,客户端去调用服务端,碰上服务端宕机或关闭,需要做降级处理,这个降级处理可以在提供服务的8001
做,也可以在调用服务的80
做,我们在80中做,与服务端8001没有关系。
如何做?
- 只需要为Feign客户端定义的接口添加一个服务降级处理的实现类即可实现解耦
未来我们要面对的异常
- 运行
- 超时
- 宕机
代码实现:
-
修改
cloud-consumer-feign-hystrix-order80
,80服务中已经有PaymentHystrixService
接口,重新新建一个类(AaymentFallbackService
)实现该接口,统一为接口里面的方法进行异常降级处理。@Component public class PaymentFallbackService implements PaymentHystrixService{ @Override public String paymentInfo_OK(Integer id){ return "-----PaymentFallbackService fall back-paymentInfo_OK ,o(╥﹏╥)o"; } @Override public String paymentInfo_TimeOut(Integer id) { return "-----PaymentFallbackService fall back-paymentInfo_TimeOut ,o(╥﹏╥)o"; } }
-
YML
server: port: 80 eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka/ #开启 feign: hystrix: enabled: true
-
PaymentHystrixService接口
@Component // 注意:当8001服务调用出错的时候采用的降级处理 @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" ,// fallback = PaymentFallbackService.class)//指定PaymentFallbackService类 public interface PaymentHystrixService { @GetMapping("/payment/hystrix/ok/{id}") public String paymentInfo_OK(@PathVariable("id") Integer id); @GetMapping("/payment/hystrix/timeout/{id}") public String paymentInfo_TimeOut(@PathVariable("id") Integer id); }
开始测试,开启cloud-eureka-server7003
,cloud-consumer-feign-hystrixorder80
两个微服务,
关闭cloud-provider-hystrixpayment8001
这个微服务,相当于此服务宕机。
- 浏览器访问:
http://localhost/consumer/payment/hystrix/timeout/1
10.12、Hystrix之服务熔断理论
断路器:相当于保险丝。
熔断机制概述
- 熔断机制是应对雪崩效应的一种微服务链路
保护机制
。 - 当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而
熔断该节点微服
务的调用,快速返回错误的响应信息。 - 当检测到该节点微服务调用响应正常后,
恢复调用链路
,这才是牛逼的功能。 - 在Spring Cloud框架里,熔断机制通过Hystrix实现,Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是
5秒内20次调用失败
,就会启动熔断机制,熔断机制的注解@HystrixCommand
。
提出此机制的相关论文链接,有兴趣的可以看看:https://martinfowler.com/bliki/CircuitBreaker.html
10.13、Hystrix之服务熔断案例
再次提一嘴一个比较好用的工具包HuTool:官网链接
前面配置了服务的降级
,下面开始配置服务的熔断
!!!
修改:cloud-provider-hystrix-payment8001
-
修改服务类
@Service public class PaymentService{ ... //=====服务熔断 @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = { @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸 }) public String paymentCircuitBreaker(@PathVariable("id") Integer id) { if(id < 0) { throw new RuntimeException("******id 不能负数"); } String serialNumber = IdUtil.simpleUUID(); return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber; } // 服务降级的兜底方法 public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) { return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~ id: " +id; } }
-
为什么这么配,可以参考官网:
https://github.com/Netflix/Hystrix/issues/674
-
如果想了解还有哪些可以配置的属性,可以看看一下Hystrix有关的配置类:
HystrixCommandProperties
-
修改控制类:
@RestController @Slf4j public class PaymentController { @Resource private PaymentService paymentService; ... //====服务熔断 @GetMapping("/payment/circuit/{id}") public String paymentCircuitBreaker(@PathVariable("id") Integer id) { String result = paymentService.paymentCircuitBreaker(id); log.info("****result: "+result); return result; } }
测试:启动cloud-provider-hystrix-payment8001
,cloud-eureka-server7003
两个服务
-
正确 :
http://localhost:8001/payment/circuit/1
-
错误 :
http://localhost:8001/payment/circuit/-1
-
我们尝试多次错误访问,再来一次正确访问,返回的还是错误得显示
-
原因:因为多次的错误访问导致该方法被
熔断
,熔断后在访问
直接就是访问的降级的方法
,等正确率上升了,被熔断的方法才会被恢复链路
。
10.14、Hystrix之服务熔断总结
熔断类型
- 熔断打开:请求不再进行调用当前服务,内部设置时钟一般为MTTR(平均故障处理时间),当打开时长达到所设时钟则进入半熔断状态。
- 熔断关闭:熔断关闭不会对服务进行熔断。
- 熔断半开:部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断。
断路器在什么情况下开始起作用:
//=====服务熔断
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
...
}
涉及到断路器的三个重要参数:
快照时间窗
:断路器确定是否打开需要统计一些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的10秒。请求总数阀值
:在快照时间窗内,必须满足请求总数阀值才有资格熔断。默认为20,意味着在10秒内,如果该hystrix命令的调用次数不足20次7,即使所有的请求都超时或其他原因失败,断路器都不会打开。错误百分比阀值
:当请求总数在快照时间窗内超过了阀值,比如发生了30次调用,如果在这30次调用中,有15次发生了超时异常,也就是超过50%的错误百分比,在默认设定50%阀值情况下,这时候就会将断路器打开。
断路器开启或者关闭的条件
- 到达以下阀值,断路器将会
开启
:
- 当满足一定的阀值的时候(默认10秒内超过20个请求次数)
- 当失败率达到一定的时候(默认10秒内超过50%的请求失败)
-
当开启的时候,所有请求都不会进行转发
-
一段时间之后(默认是5秒),这个时候断路器是半开状态,会让其中一个请求进行转发。如果成功,断路器会
关闭
,若失败,继续开启。
断路器打开之后
-
1、再有请求调用的时候,将不会调用主逻辑,而是直接调用降级fallback,通过断路器,实现了自动地发现错误并将降级逻辑切换为主逻辑,减少响应延迟的效果。
-
2、原来的主逻辑要如何恢复呢?
-
对于这一问题,hystrix也为我们实现了自动恢复功能。
-
当断路器打开,对主逻辑进行熔断之后,hystrix会启动一个休眠时间窗,在这个时间窗内,降级逻辑是临时的成为主逻辑,当休眠时间窗到期,断路器将进入半开状态,释放一次请求到原来的主逻辑上,如果此次请求正常返回,那么断路器将继续闭合,主逻辑恢复,如果这次请求依然有问题,断路器继续进入打开状态,休眠时间窗重新计时。
-
所有的配置如下:
@HystrixCommand(fallbackMethod = "fallbackMethod",
groupKey = "strGroupCommand",
commandKey = "strCommand",
threadPoolKey = "strThreadPool",
commandProperties = {
// 设置隔离策略,THREAD 表示线程池 SEMAPHORE:信号池隔离
@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
// 当隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
@HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
// 配置命令执行的超时时间
@HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
// 是否启用超时时间
@HystrixProperty(name = "execution.timeout.enabled", value = "true"),
// 执行超时的时候是否中断
@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
// 执行被取消的时候是否中断
@HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
// 允许回调方法执行的最大并发数
@HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
// 服务降级是否启用,是否执行回调函数
@HystrixProperty(name = "fallback.enabled", value = "true"),
// 是否启用断路器
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为 20 的时候,如果滚动时间窗(默认10秒)内仅收到了19个请求, 即使这19个请求都失败了,断路器也不会打开。
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
// 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过 circuitBreaker.requestVolumeThreshold 的情况下,如果错误请求数的百分比超过50, 就把断路器设置为 "打开" 状态,否则就设置为 "关闭" 状态。
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 该属性用来设置当断路器打开之后的休眠时间窗。 休眠时间窗结束之后,会将断路器置为 "半开" 状态,尝试熔断的请求命令,如果依然失败就将断路器继续设置为 "打开" 状态,如果成功就设置为 "关闭" 状态。
@HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5000"),
// 断路器强制打开
@HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
// 断路器强制关闭
@HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
// 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
@HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
// 该属性用来设置滚动时间窗统计指标信息时划分"桶"的数量,断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个 "桶" 来累计各度量值,每个"桶"记录了一段时间内的采集指标。
// 比如 10 秒内拆分成 10 个"桶"收集这样,所以 timeinMilliseconds 必须能被 numBuckets 整除。否则会抛异常
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
// 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为 false, 那么所有的概要统计都将返回 -1。
@HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"),
// 该属性用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
@HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
// 该属性用来设置百分位统计滚动窗口中使用 “ 桶 ”的数量。
@HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
// 该属性用来设置在执行过程中每个 “桶” 中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,
// 就从最初的位置开始重写。例如,将该值设置为100, 滚动窗口为10秒,若在10秒内一个 “桶 ”中发生了500次执行,
// 那么该 “桶” 中只保留 最后的100次执行的统计。另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
@HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
// 该属性用来设置采集影响断路器状态的健康快照(请求的成功、 错误百分比)的间隔等待时间。
@HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
// 是否开启请求缓存
@HystrixProperty(name = "requestCache.enabled", value = "true"),
// HystrixCommand的执行和事件是否打印日志到 HystrixRequestLog 中
@HystrixProperty(name = "requestLog.enabled", value = "true"),
},
threadPoolProperties = {
// 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
@HystrixProperty(name = "coreSize", value = "10"),
// 该参数用来设置线程池的最大队列大小。当设置为 -1 时,线程池将使用 SynchronousQueue 实现的队列,否则将使用 LinkedBlockingQueue 实现的队列。
@HystrixProperty(name = "maxQueueSize", value = "-1"),
// 该参数用来为队列设置拒绝阈值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
// 该参数主要是对 LinkedBlockingQueue 队列的补充,因为 LinkedBlockingQueue 队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
}
)
public String doSomething() {
...
}
10.15、Hystrix工作流程最后总结
服务限流 :后面高级篇讲解alibaba的Sentinel说明
Hystrix是如何工作的呢?
- 官方解释连接:
https://github.com/Netflix/Hystrix/wiki/How-it-Works
- 工作流程图如下:
就是对上面流程图的具体解释,如果想详细了解的可以查看官方解释,很具体,只不过是英文的,如果想要快速了解,可以听视屏,对应视屏链接:https://www.bilibili.com/video/BV18E411x7eT?p=62
10.16、Hystrix图形化Dashboard搭建
除了隔离依赖服务的调用以外,Hystrix还提供了准实时的调用监控(Hystrix Dashboard),Hystrix会持续地记录所有通过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。
Netflix通过hystrix-metrics-event-stream
项目实现了对以上指标的监控,Spring Cloud也提供了Hystrix Dashboard的整合,对监控内容转化成可视化界面。
我们创建一个微服务来实现这个功能:仪表盘9001
1、新建cloud-consumer-hystrix-dashboard9001
2、POM
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、YML
server:
port: 9001
4、主启动
@SpringBootApplication
@EnableHystrixDashboard // 添加这个注解
public class HystrixDashboardMain9001
{
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardMain9001.class, args);
}
}
5、所有Provider微服务提供类(8001/8002
)都需要监控依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
6、启动cloud-consumer-hystrix-dashboard9001
该微服务后续将监控微服务8001
- 浏览器输入:
http://localhost:9001/hystrix
10.17、 Hystrix图形化Dashboard监控实战
我们监控cloud-provider-hystrix-payment8001微服务,要对这个微服务的主启动类进行修改:
- 注意:新版本Hystrix需要在主启动类PaymentHystrixMain8001中指定监控路径
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001
{
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
/**
*此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
*ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
*只要在自己的项目里配置上下面的servlet就可以了
*否则,Unable to connect to Command Metric Stream 404
*/
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
监控测试
启动1个eureka:cloud-eureka-server7003
启动cloud-provider-hystrixpayment8001
启动cloud-consumer-hystrix-dashboard9001
打开监控页面:http://localhost:9001/hystrix
- 在监控页面中填写监控的地址:
http://localhost:8001/hystrix.stream
测试地址
-
http://localhost:8001/payment/circuit/1
-
http://localhost:8001/payment/circuit/-1
实心圆:共有两种含义
-
它通过
颜色
的变化代表了实例的健康程度,它的健康度从绿色<黄色<橙色<红色
递减。 -
它的
大小
也会根据实例的请求流量
发生变化,流量越大该实心圆就越大。 -
所以通过该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。
线
- 曲线:用来记录2分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。
整图说明:
监控多个的情形是这样的: