🔰 学习视频 🔰
尚硅谷SpringCloud框架开发教程(SpringCloudAlibaba微服务分布式架构丨Spring Cloud)
集数:47—64
🔰 学习格言 🔰
不在能知,乃在能行。
🔰 学习笔记 🔰
🔰 项目地址 🔰
https://gitee.com/zqcliudaliuda/cloud2021
文章目录
一、概述
1.1 实际问题
🔶 分布式系统面临的问题
复杂分布式体系结构中的应用程序有数10个依赖关系,每个依赖关系在某些时候将不可避免地失败。
左图中的请求需要调用A,P, H,I四个服务,如果一切顺利则没有什么问题,关键是如果I服务超时会出现什么情况呢?
🔶 服务雪崩
多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的"扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引|起系统崩溃,所谓的“雪崩效应”。
对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几秒钟内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障。这些都表示需要对故障和延迟进行隔离和管理,以便单个依赖关系的失败,不能取消整个应用程序或系统。
所以,通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫雪崩。
1.2 Hystrix简介
Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
“断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(FallBack) ,而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。
https://github.com/Netflix/hystrix/wiki
二、重要概念
2.1 服务降级 FallBack
服务器忙,请稍后再试,不让客户端等待并立刻返回一个友好提示。
哪些情况会触发降级
- 程序运行异常
- 超时
- 服务熔断触发服务降级
- 线程池/信号量打满导致服务降级
2.2 服务熔断
类比保险丝达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示。
就是保险丝,服务的降级->进而熔断->恢复调用链路。
2.3 服务限流
秒杀高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟N个,有序进行。
三、案例
3.1 构建简单项目
🔶 调整Eureka7001
启动两个Eureka太麻烦了,所以调整Eureka7001为单机模式,以后在测试的时候只需要启动一个服务。
【SpringCloud】Eureka服务注册与发现、Eureka集群配置、微服务集群发布到Eureka
修改配置文件:
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com # eureka服务端的实例名称
client:
register-with-eureka: false # false表示不向注册中心注册自己
fetch-registry: false # false表示自己就是注册中心,职责就是维护服务实例,并不需要去检索服务
service-url:
# 集群指向其他eureka
# defaultZone: http://eureka7002.com:7002/eureka/
# 单机指向7001自己
defaultZone: http://eureka7001.com:7001/eureka/
🔶 新建项目
新建maven项目cloud-provider-hystrix-payment8001
🔶 POM
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.zqc.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>true</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
🔶 application.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/
🔶 主启动类
@SpringBootApplication
@EnableEurekaClient
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
}
🔶 业务类
节约时间,内容就简单点写。
一个正常可调用方法,一个会超时的方法。
@Service
public class PaymentService {
// 正常访问,肯定ok`在这里插入代码片`
public String paymentInfo_OK(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_OK,id: " + id;
}
// 模拟会出错
public String paymentInfo_Timeout(Integer id) {
int timeNumber = 3;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_Timeout,id: " + id + " 耗时(秒):" + timeNumber;
}
}
🔶 控制类
@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) {
String s = paymentService.paymentInfo_OK(id);
log.info("---------result: " + s);
return s;
}
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
String s = paymentService.paymentInfo_Timeout(id);
log.info("---------result: " + s);
return s;
}
}
🔶 正常测试
先启动eureka7001,再启动刚刚的8001。
访问:http://localhost:8001/payment/hystrix/ok/1
线程池:http-nio-8001-exec-1 paymentInfo_OK,id: 1
访问:http://localhost:8001/payment/hystrix/timeout/1
结果只是返回的慢一点,需要耗时3s
线程池:http-nio-8001-exec-2 paymentInfo_Timeout,id: 1 耗时(秒):3
3.2 高并发测试1
以上述的测试为根基进行测试,上述在非高并发情形下,还能勉强满足。
🔶 Jmeter压测测试
开启Jmeter,来20000个并发压死8001,20000个请求都去访问paymentInfo_TimeOut服务
Jmeter参考教程:https://blog.youkuaiyun.com/yaorongke/article/details/82799609
右键Test Plan——Add——Thread——Thread Group
设置线程数和循环次数,总并发量 200*100=20000
右键Thread Group——Add——Sampler——HTTP Request
设置ip、端口号和访问路径(http://localhost:8001/payment/hystrix/timeout/1),开始运行。
此时,运行20000个并发,浏览器访问http://localhost:8001/payment/hystrix/ok/1时,不会立即刷新,会导致它变卡顿。
🔶 Jmeter压测结论
变卡原因:tomcat的默认工作线程数被打满了,没有多余的线程来分解压力和处理。
上面还只是服务提供者8001自己测试,假如此时外部的消费者80也来访问,那消费者只能干等,最终导致消费端80不满意,服务端8001直接被拖死。
3.3 高并发测试2
新建一个80客户端加入测试。
🔶 新建项目
新建maven项目cloud-consumer-feign-hystrix-order80
。
🔶 POM
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.zqc.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>true</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
🔶 application.yml
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka
🔶 主启动类
@SpringBootApplication
@EnableFeignClients
public class OrderHystrixMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderHystrixMain80.class, args);
}
}
🔶 业务类 service
之前8001注册在erueka服务器上的服务名为CLOUD-PROVIDER-HYSTRIX-PAYMENT
,所以采用接口的方式把8001的服务写在80消费者里面。
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT")
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
🔶 控制类 controller
调用service接口对应的方法,就会找到CLOUD-PROVIDER-HYSTRIX-PAYMENT
服务内对应的方法。
@RestController
@Slf4j
public class OrderHystrixController {
@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}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
}
🔶 测试
8001自测:
http://localhost:8001/payment/hystrix/ok/1 成功
http://localhost:8001/payment/hystrix/timeout/1 成功
80测试:
http://localhost/consumer/payment/hystrix/ok/1 成功
http://localhost/consumer/payment/hystrix/timeout/1 失败
失败原因:服务超时。
如果此时加入高并发测试,访问http://localhost/consumer/payment/hystrix/ok/1 也将变慢。
故障原因及现象:8001同一层次的其他接口被困死,因为tomcat线程池里面的工作线程已经被挤占完毕。80此时调用8001,客户端访问响应缓慢,转圈圈。
正因为有上述故障或不佳表现,才有降级/容错/限流等技术诞生。
3.4 解决问题的要求
超时导致服务器变慢(转圈):超时不再等待
出错(宕机或程序运行出错):出错要有兜底
解决:
- 对方服务(8001)超时了,调用者(80)不能一直卡死等待,必须有服务降级
- 对方服务(8001)宕机了,调用者(80)不能一直卡死等待,必须有服务降级
- 对方服务(8001)没问题,调用者(80)自己有故障或有自我要求(如,自己的等待时间小于服务提供者),自己降级处理
3.5 服务降级
3.5.1 服务端8001
解决8001自身服务问题,设置自身调用超时时间峰值,峰值内可以正常运行,超过时间需要有兜底的方法处理,作服务降级fallback。
向调用方返回一个符合预期的、可处理的备选响应(Fallback),而不是长时间的等待或者抛出调用方无法处理的异常。
🔶 修改8001的PaymentService
一旦调用服务方法失败并抛出错误信息后,会自动调用@HystrixCommand
标注好的fallbackMthod
调用类中的指定方法。
@Service
public class PaymentService {
// 正常访问,肯定ok
public String paymentInfo_OK(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_OK,id: " + id;
}
@HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
// 规定超时的时间为3s
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String paymentInfo_Timeout(Integer id) {
// 设置延迟时间为5
int timeNumber = 5;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_Timeout,id: " + id + " 耗时(秒):" + timeNumber;
}
// 上面的方法出问题,这个方法兜底
public String paymentInfo_TimeoutHandler(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " 8001系统繁忙或者运行报错,请稍后再试,id: " + id;
}
}
🔶 修改8001主启动类,添加注解@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
}
🔶 启动测试1
访问:http://localhost:8001/payment/hystrix/timeout/1
线程池:hystrix-PaymentService-2 8001系统繁忙或者运行报错,请稍后再试,id: 1
原因:因为该方法延迟的时间为5s,而设置的超时时间为3s,所以该方法响应失败,进而运行了兜底方法。
🔶 启动测试2
将8001的PaymentService
中的超时改成报错,看看测试的结果如何
运行后,结果相同,都调用了兜底方案。
3.5.2 客户端80
80订单服务,也要客户端降级保护。
🔶 修改yml
开启hystrix
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);
}
}
🔶 修改业务类
添加fallback方法与设置。
@RestController
@Slf4j
public class OrderHystrixController {
@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}")
@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod", commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value = "1500")
})
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id)
{
return "消费者80,对方支付系统繁忙,请稍后再试";
}
}
🔶 测试
保证8001服务的paymentInfo_Timeout
方法延迟5s。依次启动7001、8001、80…
访问:http://localhost/consumer/payment/hystrix/timeout/1
消费者80,对方支付系统繁忙,请稍后再试
原因:因为客户端(消费端)只等待1.5s,而服务端需要等待5s,超过了客户端的等待时间,所以客户端只能选择兜底方案。如果客户端的代码出现问题,同样会选择兜底方案。
3.5.3 默认fallback
每个业务方法对应一个兜底的方法,会导致代码膨胀。所以,可以设计一个默认的fallback方法,当没有指定特定的fallback方法就选择默认的fallback方法。
通用和独享的各自分开,避免代码膨胀,合理减少了代码量。
以80为例进行修改:
🔶 修改控制类
为控制类添加注解,@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
,指明默认的callback方法为payment_Global_FallbackMethod
,并在需要callback的方法前面添加注解@HystrixCommand
;最后编写默认的callback方法的内容。
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {
@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}")
// @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod", commandProperties = {
// @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value = "1500")
// })
@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,对方支付系统繁忙,请稍后再试";
}
// 下面时全局fallback方法
public String payment_Global_FallbackMethod() {
return "Global异常处理信息,请稍后再试!";
}
}
🔶 测试
访问:http://localhost/consumer/payment/hystrix/timeout/1
Global异常处理信息,请稍后再试!
3.5.4 统配服务降级
对于服务端的每一个方法,都需要在客户端为其创建与其方法名的相同接口,且在控制器调用时为其设定fallback方法(或是默认的fallback方法),代码耦合度高。其实,只要对某一个微服务指定一个fallback方法就更简单了。
常见的异常:运行时异常、超时、服务端宕机
🔶 新建服务类 PaymentFallbackService
根据cloud-consumer-feign-hystrix-order80已经有的PaymentHystrixService接口,新建一个类PaymentFallbackService实现该接口,同意为借口里面的方法进行异常处理。
@Component
public class PaymentFallbackService implements PaymentHystrixService{
@Override
public String paymentInfo_OK(Integer id) {
return "-----------PaymentFallbackService fall back paymentInfo_OK";
}
@Override
public String paymentInfo_TimeOut(Integer id) {
return "-----------PaymentFallbackService fall back paymentInfo_TimeOut";
}
}
🔶 application.yml
开启hystrix
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka
feign:
hystrix:
enabled: true
🔶 修改服务类
为微服务指定fallbcak,@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentFallbackService.class)
。
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
🔶 测试
依次启动7001、8001、80
访问:http://localhost/consumer/payment/hystrix/ok/1
线程池:http-nio-8001-exec-5 paymentInfo_OK,id: 1
关闭8001服务端,模拟服务器突然宕机。
访问:http://localhost/consumer/payment/hystrix/ok/1
-----------PaymentFallbackService fall back paymentInfo_OK
虽然服务端提供者已经宕机 ,但是我们做了服务降级处理, 让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器。
3.5 服务熔断
3.5.1 熔断机制概述
熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。
在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是@HystrixCommand
.
熔断类型
-
熔断打开:请求不再进行调用当前服务,内部设置时钟一般为MTTR (平均故障处理时间),当打开时长达到所设时钟则进入半熔断状态
-
熔断关闭:熔断关闭不会对服务进行熔断
-
熔断半开:部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断
3.5.2 项目测试
修改项目cloud-provider-hystrix-payment8001
🔶 修改service
新增服务熔断的配置和方法paymentCircuitBreaker
、paymentCircuitBreaker_fallback
。
@Service
public class PaymentService {
// ===================服务降级===================
// 正常访问,肯定ok
public String paymentInfo_OK(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_OK,id: " + id;
}
@HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
// 规定超时的时间为3s
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String paymentInfo_Timeout(Integer id) {
// 设置延迟时间为5
int timeNumber = 5;
//int timeNumber = 0;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_Timeout,id: " + id + " 耗时(秒):" + timeNumber;
}
// 上面的方法出问题,这个方法兜底
public String paymentInfo_TimeoutHandler(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " 8001系统繁忙或者运行报错,请稍后再试,id: " + id;
}
// ===================服务熔断===================
@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"), // 失败率达到多少后要跳闸
// 开启断路器,在10s的时间窗口期,10次请求中有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不能负数,请稍后再试,id: " + id;
}
}
涉及到断路器的三个重要参数:快照时间窗、请求总数阀值、错误百分比阀值。
- 快照时间窗:断路器确定是否打开需要统计一些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的10秒。
- 请求总数阀值:在快照时间窗内,必须满足请求总数阀值才有资格熔断。默认为20,意味着在10秒内,如果该hystrix命令的调用次数不足20次,即使所有的请求都超时或其他原因失败,断路器都不会打开。
- 错误百分比阀值:当请求总数在快照时间窗内超过了阀值,比如发生了30次调用,如果在这30次调用中,有15次发生了超时异常,也就是超过50%的错误百分比,在默认设定50%阀值情况下,这时候就会将断路器打开。
🔶 修改controller
添加service中paymentCircuitBreaker
的控制方法。
@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) {
String s = paymentService.paymentInfo_OK(id);
log.info("---------result: " + s);
return s;
}
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
String s = paymentService.paymentInfo_Timeout(id);
log.info("---------result: " + s);
return s;
}
// ===================服务熔断===================
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
String result = paymentService.paymentCircuitBreaker(id);
log.info("----result: " + result);
return result;
}
}
🔶 测试1
依次启动:7001、8001,测试代码是否正确
访问:http://localhost:8001/payment/circuit/1
hystrix-PaymentService-10 调用成功,流水号:734e2f3eeecd43a9b1d565f541957e7e
访问:http://localhost:8001/payment/circuit/-1
id不能负数,请稍后再试,id: -1
🔶 测试2
依次启动:7001、8001.
访问:http://localhost:8001/payment/circuit/1
hystrix-PaymentService-10 调用成功,流水号:734e2f3eeecd43a9b1d565f541957e7e
10s内连续访问10次:http://localhost:8001/payment/circuit/-1
id不能负数,请稍后再试,id: -1
访问:http://localhost:8001/payment/circuit/1
id不能负数,请稍后再试,id: 1
由于服务熔断,正确的输入也会使用fallback方法。等待一会再次访问正确链接,结果恢复正确。
3.6 服务限流
略
3.7 工作流程
https://github.com/Netflix/Hystrix/wiki/How-it-Works
步骤1:构造HystrixCommand
或HystrixObservableCommand
对象,某些请求对其依赖。
步骤2:选择构造器对应的方法发送命令,请求。
步骤3:查看缓存,如果缓冲启动且命中直接返回,如果没有响应进入步骤4。
步骤4:查看断路器是否打开(保险丝是否打开),如果断路器打开则调用步骤8的fallback方法,否则进入步骤5。无论失败还是成功,都将执行步骤7。
步骤5:线程池、请求队列都满了调用步骤8的fallback方法,否则进入步骤6。
步骤6:执行构造方法或run方法,如果执行错误或超时,则调用步骤8的fallback方法,否则将执行完成。无论失败还是成功,都将执行步骤7。
步骤7:将执行的完成情况(完成、执行错误或超时)返回给断路器进行评估。
步骤8:执行fallback方法。
四、DashBoard
除了隔离依赖服务的调用以外,Hystrix还提供 了准实时的调用监控(Hystrix Dashboard),Hystrix会持续地记录所有通过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。Netflix通过hystrix-metrics-event-stream项目实现了对以上指标的监控。Spring Cloud也提供了Hystrix Dashboard的整合,对监控内容转化成可视化界面。
4.1 项目构建
🔶 项目搭建
搭建maven项目cloud-consumer-hystrix-dashboard9001
🔶 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>
🔶 application.yml
server:
port: 9001
🔶 主启动类
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardMain9001.class, args);
}
}
🔶 被监控服务的依赖
所有被监控的服务都需要添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
🔶 测试
依次启动7001、8001、9001
访问:http://localhost:9001/hystrix
4.2 演示
🔶 修改8001主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
/**
* 此配置是为了服务监控而配置,与服务容错本身无观,springCloud 升级之后的坑
* ServletRegistrationBean因为springboot的默认路径不是/hystrix.stream
* 只要在自己的项目中配置上下面的servlet即可
* @return
*/
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
🔶 测试
依次启动:7001、8001、9001
访问5次:http://localhost:8001/payment/circuit/1
访问5次:http://localhost:8001/payment/circuit/2
可以查看到变化:
🔶 说明
- 七色:Success | Short-Circuited | Bad Request | Timeout | Rejected | Failure | Error
- 一圈:实心圆:共有两种含义。它通过颜色的变化代表了实例的健康程度,它的健康度从绿色<黄色<橙色<红色递减。该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。所以通过该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。