- 当调用出现问题时,开启一个时间窗(10s)
- 在这个时间窗内,统计调用、用次数是否达到最小请求数?
- 如果没有达到,则重置统计信息,回到第1步
- 如果达到了,则统计失败的请求数占所有请求数的百分比,是否达到阈值?
- 如果达到,则跳闸(不再请求对应服务)
- 如果没有达到,则重置统计信息,回到第1步
- 如果跳闸,则会开启一个活动窗口(默认5s),每隔5s,Hystrix会让一个请求通过,到达那个问题服务,看 是否调用成功,如果成功,重置断路器回到第1步,如果失败,回到第3步。
/**
* 8秒钟内,请求次数达到2个,并且失败率在50%以上,就跳闸
* 跳闸后活动窗⼝设置为3s
*/
@GetMapping("/checkStateTimeoutFallback/{userId}")
@HystrixCommand(
// 线程池标识,要保持唯一,不唯一的话就共用了
threadPoolKey = "findResumeOpenStateTimeoutFallback",
// 线程池属性细节配置
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2"), // 线程数
@HystrixProperty(name = "maxQueueSize", value = "20") // 等待队列长度
},
// commandProperties 熔断的一些细节属性配置
commandProperties = {
// 每一个属性都是一个HystrixProperty
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"),
// hystrix高级配置,定制工作过程细节
// 统计时间窗口定义
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "8000"),
// 统计时间窗口内的最小请求数
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
// 统计时间窗口内的错误数量百分比阈值
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 自我修复时的活动时间窗口长度
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "3000")
},
fallbackMethod = "myFallback" // 回退方法
)
public Integer findResumeOpenStateTimeoutFallback(@PathVariable Long userId) {
// 使用Ribbon不需要我们自己获取服务实例,然后选择一个那种方式去访问了(自己负载均衡)
String url = "http://lagou-service-resume/resume/openstate/" + userId; // 指定服务名
Integer forObject = restTemplate.getForObject(url, Integer.class);
return forObject;
}
我们上述通过注解进行的配置也可以配置在配置文件中
# 配置熔断策略:
hystrix:
command:
default:
circuitBreaker:
# 强制打开熔断器,如果该属性设置为true,强制断路器进⼊打开状态,将会拒绝所有的请求。 默认false关闭的
forceOpen: false
# 触发熔断错误⽐例阈值,默认值50%
errorThresholdPercentage: 50
# 熔断后休眠时⻓,默认值5秒
sleepWindowInMilliseconds: 3000
# 熔断触发最⼩请求次数,默认值是20
requestVolumeThreshold: 2
execution:
isolation:
thread:
# 熔断超时设置,默认为1秒
timeoutInMilliseconds: 2000
基于springboot的健康检查观察跳闸状态(自动投递微服务暴露健康检查细节)
# springboot中暴露健康检查等断点接⼝
management:
endpoints:
web:
exposure:
include: "*"
# 暴露健康接⼝的细节
endpoint:
health:
show-details: always
访问健康检查接口:http://localhost:8090/actuator/health
hystrix正常工作状态
跳闸状态
活动窗口内自我修复