SpringBoot服务熔断之Hystrix案例
一、相关依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
二、案例核心代码
service相关代码
涉及到断路器的三个重要参数:快照时间窗、请求总数阀值、错误百分比阀值。
快照时间窗:断路器确定是否打开需要统计一些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的10秒。
请求总数阀值:在快照时间窗内,必须满足请求总数阀值才有资格熔断。默认为20,意味着在10秒内,如果该hystrix命令的调用次数不够20次,即使所有的请求都超时或者其他原因失败,断路器都不会打开。
错误百分比阀值:当请求总数在快照时间窗口内超过了阀值,比如发生了30次调用,如果在30次调用中有15次异常,也就是超过50%的错误百分比,在默认设定50%阀值的情况下,这时候断路器就会打开。
当开启断路器的时候,所有请求都不会进行转发,一段时间后(默认是5秒),这时候断路器是半开状态的,会让其中一个请求转发,如果成功,断路器就会关闭,若失败,继续开启。
@HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {//10秒钟内有10次请求,6次失败则熔断@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() + "调用成功,流水号为:" + serialNumber;}public String paymentCircuitBreakerFallback(@PathVariable("id") Integer id) {return "服务熔断,请稍后再试" + id;}
controller测试代码
@GetMapping("/payment/circuit/{id}")public String paymentCircuitBreaker(@PathVariable("id") Integer id){String result=paymentService.paymentCircuitBreaker(id);log.info("result:{}",result);return result;}
三、测试案例
1)、正常情况下(未触发断路器)
正数时:
负数时:
2)、断路器开启时
频繁刷新负数测试(10秒内超过6次失败触发熔断)
再访问正数时:发现也出错了,证明断路器开启了
过一段时间再访问:又回复了正常