八、 深入理解hystrix的短路器执行原理
circuit breaker:短路器,快速熔断(一旦后端服务故障,立刻熔断,阻止对其的访问)
8.1 短路器的流量在一定的时间窗口内超过了一定的阈值
HystrixCommandProperties.circuitBreakerRequestVolumeThreshold()
短路器的流量在一定的时间窗口内超过了一定的阈值。举个例子,要求在10s内,经过短路器的流量必须达到20个;在10s内,经过短路器的流量才10个,那么根本不会去判断要不要短路
//(2)circuitBreaker.requestVolumeThreshold:经过短路器的流量超过了一定的阈值(默认10s 20个) .withCircuitBreakerRequestVolumeThreshold(20) |
8.2 短路器统计到的异常调用的占比超过了一定的阈值HystrixCommandProperties.circuitBreakerErrorThresholdPercentage()
如果达到了上面8.1的要求,比如说在10s内,经过短路器的流量(只要执行一个command,这个请求就一定会经过短路器),达到了30个;同时其中异常的访问数量,占到了一定的比例,比如说60%的请求都是异常(报错,timeout,reject),会开启短路
//(3)circuitBreaker.errorThresholdPercentage:短路器统计到的异常调用的占比超过了一定的阈值(50) .withCircuitBreakerErrorThresholdPercentage(50) |
8.3 短路器从close状态转换到open状态
8.4 短路器打开不调用后端服务,直接走fallback降级
短路器打开的时候,所有经过该短路器的请求全部被短路,不调用后端服务,直接走fallback降级
8.5 一段时间后半开、一条经过、自动恢复、到Close状态
HystrixCommandProperties.circuitBreakerSleepWindowInMilliseconds()
经过了一段时间之后,HystrixCommandProperties.circuitBreakerSleepWindowInMilliseconds(),会half-open,让一条请求经过短路器,看能不能正常调用。如果调用成功了,那么就自动恢复,转到close状态
短路器,会自动恢复的,half-open,半开状态
//(4)circuitBreaker.sleepWindowInMilliseconds:短路器,会自动恢复的,half-open,半开状态,默认5s .withCircuitBreakerSleepWindowInMilliseconds(5000) |
8.6 circuit breaker短路器的配置
(1)circuitBreaker.enabled
控制短路器是否允许工作,包括跟踪依赖服务调用的健康状况,以及对异常情况过多时是否允许触发短路,默认是true
HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(boolean value)
//(1)circuitBreaker.enabled:控制短路器是否允许工作 .withCircuitBreakerEnabled(true) |
(2)circuitBreaker.requestVolumeThreshold
设置一个rolling window,滑动窗口中,最少要有多少个请求时,才触发开启短路
举例来说,如果设置为20(默认值),那么在一个10秒的滑动窗口内,如果只有19个请求,即使这19个请求都是异常的,也是不会触发开启短路器的
HystrixCommandProperties.Setter()
.withCircuitBreakerRequestVolumeThreshold(int value)
//(2)circuitBreaker.requestVolumeThreshold:经过短路器的流量超过了一定的阈值(默认10s 20个) .withCircuitBreakerRequestVolumeThreshold(20) |
(3)circuitBreaker.sleepWindowInMilliseconds
设置在短路之后,需要在多长时间内直接reject请求,然后在这段时间之后,再重新导holf-open状态,尝试允许请求通过以及自动恢复,默认值是5000毫秒
HystrixCommandProperties.Setter()
.withCircuitBreakerSleepWindowInMilliseconds(int value)
//(3)circuitBreaker.sleepWindowInMilliseconds:短路器,会自动恢复的,half-open,半开状态,默认5s .withCircuitBreakerSleepWindowInMilliseconds(5000) |
(4)circuitBreaker.errorThresholdPercentage
设置异常请求量的百分比,当异常请求达到这个百分比时,就触发打开短路器,默认是50,也就是50%
HystrixCommandProperties.Setter()
.withCircuitBreakerErrorThresholdPercentage(int value)
//(4)circuitBreaker.errorThresholdPercentage:短路器统计到的异常调用的占比超过了一定的阈值(50) .withCircuitBreakerErrorThresholdPercentage(50) |
(5)circuitBreaker.forceOpen(不推荐生产环境使用)
如果设置为true的话,直接强迫打开短路器,相当于是手动短路了,手动降级,默认false
HystrixCommandProperties.Setter()
.withCircuitBreakerForceOpen(boolean value)
//(5)circuitBreaker.forceClosed:强迫关闭短路器 //.withCircuitBreakerForceClosed(true) |
(6)circuitBreaker.forceClosed
如果设置为ture的话,直接强迫关闭短路器,相当于是手动停止短路了,手动升级,默认false
HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(boolean value)
//(6)circuitBreaker.forceOpen:直接强迫打开短路器 //.withCircuitBreakerForceOpen(true) |