Hystrix配置
@Configuration
public class HystrixConfig {
@Bean
public HystrixCommandAspect hystrixCommandAspect() {
return new HystrixCommandAspect();
}
/**
* 向监控中心Dashboard发送stream消息
*/
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
ServletRegistrationBean registrationBean =
new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registrationBean.addUrlMappings("/hystrix.stream");
return registrationBean;
}
}
Hystrix配置参数讲解:
// 熔断器在整个统计时间内是否开启的阀值
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 至少有3个请求才进行熔断错误比率计算
/**
* 设置在一个滚动窗口中,打开断路器的最少请求数。
比如:如果值是20,在一个窗口内(比如10秒),收到19个请求,即使这19个请求都失败了,断路器也不会打开。
*/
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"),
//当出错率超过50%后熔断器启动
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 熔断器工作时间,超过这个时间,先放一个请求进去,成功的话就关闭熔断,失败就再等一段时间
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
/**
* 设置存活时间,单位分钟。如果coreSize小于maximumSize,那么该属性控制一个线程从实用完成到被释放的时间.
*/
@HystrixProperty(name = "coreSize", value = "30"),
/**
* BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。
*/
@HystrixProperty(name = "maxQueueSize", value = "101"),
/**
我们知道,线程池内核心线程数目都在忙碌,再有新的请求到达时,线程池容量可以被扩充为到最大数量。
等到线程池空闲后,多于核心数量的线程还会被回收,此值指定了线程被回收前的存活时间,默认为 2,即两分钟。
*/
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
/**
* 设置队列拒绝的阈值,即使maxQueueSize还没有达到
*/
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
// 滑动统计的桶数量
/**
* 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
*那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认1
*/
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
// 设置滑动窗口的统计时间。熔断器使用这个时间
/** 设置统计的时间窗口值的,毫秒值。
circuit break 的打开会根据1个rolling window的统计来计算。
若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,
每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
**/
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
fallbackMethod:方法执行时熔断、错误、超时时会执行的回退方法,需要保持此方法与 Hystrix 方法的签名和返回值一致。
defaultFallback:默认回退方法,当配置 fallbackMethod 项时此项没有意义,另外,默认回退方法不能有参数,返回值要与 Hystrix方法的返回值相同。
对Hystrix服务降级和熔断进行测试,3个例子。
@RestController
@RequestMapping("/hystrix1")
@DefaultProperties(defaultFallback = "defaultFail")
public class HystrixController1 {
@HystrixCommand(fallbackMethod = "fail1")
@GetMapping("/test1")
public String test1() {
throw new RuntimeException();
}
private String fail1() {
System.out.println("fail1");
return "fail1";
}
@HystrixCommand(fallbackMethod = "fail2")
@GetMapping("/test2")
public String test2() {
throw new RuntimeException();
}
@HystrixCommand(fallbackMethod = "fail3")
private String fail2() {
System.out.println("fail2");
throw new RuntimeException();
}
@HystrixCommand
private String fail3() {
System.out.println("fail3");
throw new RuntimeException();
}
private String defaultFail() {
System.out.println("default fail");
return "default fail";
}
}
当访问http://localhost:8082/hystrix1/test1
抛出异常,服务降级返回fail1。
当访问http://localhost:8082/hystrix1/test2
抛出异常,服务不断降级返回default fail。

@RestController
@RequestMapping("/hystrix2")
@DefaultProperties(defaultFallback = "defaultFail")
public class HystrixController2 {
@HystrixCommand(commandProperties =
{
// 熔断器在整个统计时间内是否开启的阀值
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 至少有3个请求才进行熔断错误比率计算
/**
* 设置在一个滚动窗口中,打开断路器的最少请求数。
比如:如果值是20,在一个窗口内(比如10秒),收到19个请求,即使这19个请求都失败了,断路器也不会打开。
*/
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"),
//当出错率超过50%后熔断器启动
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 熔断器工作时间,超过这个时间,先放一个请求进去,成功的话就关闭熔断,失败就再等一段时间
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
// 统计滚动的时间窗口
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
@GetMapping("/test1")
public String test1(@RequestParam("id") Integer id) {
System.out.println("id:" + id);
if (id % 2 == 0) {
throw new RuntimeException();
}
return "test_" + id;
}
private String defaultFail() {
System.out.println("default fail");
return "default fail";
}
}
当访问1次http://localhost:8082/hystrix2/test1?id=1
和2次http://localhost:8082/hystrix2/test1?id=2
,错误率达66%超过了设置的50%。服务进入熔断。

下次请求http://localhost:8082/hystrix2/test1?id=2
会进入熔断策略,返回default fail

如果在5s之后,下一次请求成功,会关闭熔断,服务恢复。


@RestController
@RequestMapping("/hystrix3")
@DefaultProperties(defaultFallback = "defaultFail")
public class HystrixController3 {
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
})
@GetMapping("/test1")
public String test1() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(1000);
return "test1";
}
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
// 滑动统计的桶数量
/**
* 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
*那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认1
*/
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
// 设置滑动窗口的统计时间。熔断器使用这个时间
/** 设置统计的时间窗口值的,毫秒值。
circuit break 的打开会根据1个rolling window的统计来计算。
若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,
每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
**/
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "15"),
/**
* BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。
*/
@HystrixProperty(name = "maxQueueSize", value = "15"),
/**
* 设置存活时间,单位分钟。如果coreSize小于maximumSize,那么该属性控制一个线程从实用完成到被释放的时间.
*/
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
/**
* 设置队列拒绝的阈值,即使maxQueueSize还没有达到
*/
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
@GetMapping("/test2")
public String test2() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(1000);
return "test2";
}
private String defaultFail() {
System.out.println("default fail");
return "default fail";
}
}
当.\ab -c 30 -n 30 http://localhost:8082/hystrix3/test1
并发30个请求。

由于没有显式配置maxQueueSize。Hystrix不会向阻塞队列里面放任务。当任务的数量超过了线程池负载的阈值,会采用拒绝任务策略。核心线程数量+初始数量=11个线程。11个线程由于线程阻塞进入了Timeout状态,后续无法正常继续执行其他任务,采取拒绝任务策略(拒绝了30-11=19个任务)。
此时服务进入到熔断状态,在5s之后,我们再发送http://localhost:8082/hystrix3/test1
请求,发现还是处于timeout状态,依旧是失败,继续保持熔断状态。

后续再发送http://localhost:8082/hystrix3/test1
请求,该请求已经进入到熔断处理。

maxQueueSize:作业队列的最大值,默认值为 -1,设置为此值时,队列会使用 SynchronousQueue,此时其 size 为0。
Hystrix 不会向队列内存放作业。如果此值设置为一个正的 int 型,队列会使用一个固定 size 的 LinkedBlockingQueue。
此时在核心线程池内的线程都在忙碌时,会将作业暂时存放在此队列内,但超出此队列的请求依然会被拒绝。
queueSizeRejectionThreshold:由于 maxQueueSize 值在线程池被创建后就固定了大小,
如果需要动态修改队列长度的话可以设置此值,
即使队列未满,队列内作业达到此值时同样会拒绝请求。
此值默认是 5,所以有时候只设置了 maxQueueSize 也不会起作用。

当.\ab -c 100 -n 100 http://localhost:8082/hystrix3/test2
并发100个请求。核心线程数是15个,加上初始的1个。核心线程数应该是16个,阻塞队列里面有15个。所以executions为31个。当线程数超过了阻塞队列的阈值,就拒绝任务,所以Rejected的数量是100-31=69个。默认情况下,在滑动窗口内,请求数量超过了20个,才计算熔断错误比率。当熔断错误比率超过了50%,采用熔断策略。

各参数意义


Hystrix属性的4中优先级
- 内置全局默认值(Global default from code)
如果下面3种都没有设置,默认是使用此种,后面用“默认值”代指这种。
- 动态全局默认属性(Dynamic global default property)
可以通过属性配置来更改全局默认值,后面用“默认属性”代指这种。
- 内置实例默认值(Instance default from code)
在代码中,设置的属性值,后面用“实例默认”来代指这种。
- 动态配置实例属性(Dynamic instance property)
可以针对特定的实例,动态配置属性值,来代替前面三种,后面用“实例属性”来代指这种。
优先级:1 < 2 < 3 < 4
命令属性
执行
execution.isolation.strategy
设置HystrixCommand.run()的隔离策略,有两种选项:
THREAD —— 在固定大小线程池中,以单独线程执行,并发请求数受限于线程池大小。
SEMAPHORE —— 在调用线程中执行,通过信号量来限制并发量。
默认值:THREAD(ExecutionIsolationStrategy.THREAD)
可选值:THREAD,SEMAPHORE
默认属性:hystrix.command.default.execution.isolation.strategy
实例属性:
hystrix.command.HystrixCommandKey.execution.isolation.strategy
实例默认的设置:
// to use thread isolation
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)
// to use semaphore isolation
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
execution.isolation.thread.timeoutInMilliseconds
设置调用者等待命令执行的超时限制,超过此时间,HystrixCommand被标记为TIMEOUT,并执行回退逻辑。
注意:超时会作用在HystrixCommand.queue(),即使调用者没有调用get()去获得Future对象。
默认值:1000(毫秒)
默认属性:hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
实例属性:hystrix.command.HystrixCommandKey.execution.isolation.thread.timeoutInMilliseconds
实例默认的设置:HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(int value)
execution.timeout.enabled
设置HystrixCommand.run()的执行是否有超时限制。
默认值:true
默认属性:hystrix.command.default.execution.timeout.enabled
实例属性:hystrix.command.HystrixCommandKey.execution.timeout.enabled
实例默认的设置:
HystrixCommandProperties.Setter()
.withExecutionTimeoutEnabled(boolean value)
execution.isolation.thread.interruptOnTimeout
设置HystrixCommand.run()的执行是否在超时发生时被中断。
默认值:true
默认属性:hystrix.command.default.execution.isolation.thread.interruptOnTimeout
实例属性:hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnTimeout
实例默认的设置:
HystrixCommandProperties.Setter()
.withExecutionIsolationThreadInterruptOnTimeout(boolean value)
execution.isolation.thread.interruptOnCancel
设置HystrixCommand.run()的执行但取消动作发生时候可以响应中断。
默认值:false
默认属性:hystrix.command.default.execution.isolation.thread.interruptOnCancel
实例属性:hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnCancel
实例默认的设置:
HystrixCommandProperties.Setter()
.withExecutionIsolationThreadInterruptOnCancel(boolean value)
execution.isolation.semaphore.maxConcurrentRequests
设置当使用ExecutionIsolationStrategy.SEMAPHORE时,HystrixCommand.run()方法允许的最大请求数。如果达到最大并发数时,后续请求会被拒绝。
信号量应该是容器(比如Tomcat)线程池一小部分,不能等于或者略小于容器线程池大小,否则起不到保护作用。
默认值:10
默认属性:hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests
实例属性:hystrix.command.HystrixCommandKey.execution.isolation.semaphore.maxConcurrentRequests
实例默认的设置:
HystrixCommandProperties.Setter()
.withExecutionIsolationSemaphoreMaxConcurrentRequests(int value)
回退
下面的属性控制HystrixCommand.getFallback()执行。这些属性对ExecutionIsolationStrategy.THREAD和ExecutionIsolationStrategy.SEMAPHORE都有效。
fallback.isolation.semaphore.maxConcurrentRequests
设置调用线程产生的HystrixCommand.getFallback()方法的允许最大请求数目。
如果达到最大并发数目,后续请求将会被拒绝,如果没有实现回退,则抛出异常。
默认值:10
默认属性:hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests
实例属性:hystrix.command.HystrixCommandKey.fallback.isolation.semaphore.maxConcurrentRequests
实例默认:
HystrixCommandProperties.Setter()
.withFallbackIsolationSemaphoreMaxConcurrentRequests(int value)
fallback.enabled
该属性决定当故障或者拒绝发生时,一个调用将会去尝试HystrixCommand.getFallback()。
默认值:true
默认属性:hystrix.command.default.fallback.enabled
实例属性:hystrix.command.HystrixCommandKey.fallback.enabled
实例默认的设置:HystrixCommandProperties.Setter()
.withFallbackEnabled(boolean value)
断路器(Circuit Breaker)
circuitBreaker.enabled
设置断路器是否起作用。
默认值:true
默认属性:hystrix.command.default.circuitBreaker.enabled
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.enabled
实例默认的设置:HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(boolean value)
circuitBreaker.requestVolumeThreshold
设置在一个滚动窗口中,打开断路器的最少请求数。
比如:如果值是20,在一个窗口内(比如10秒),收到19个请求,即使这19个请求都失败了,断路器也不会打开。
默认值:20
默认属性:hystrix.command.default.circuitBreaker.requestVolumeThreshold
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.requestVolumeThreshold
实例默认的设置:HystrixCommandProperties.Setter()
.withCircuitBreakerRequestVolumeThreshold(int value)
circuitBreaker.sleepWindowInMilliseconds
设置在回路被打开,拒绝请求到再次尝试请求并决定回路是否继续打开的时间。
默认值:5000(毫秒)
默认属性:hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.sleepWindowInMilliseconds
实例默认的设置:
HystrixCommandProperties.Setter()
.withCircuitBreakerSleepWindowInMilliseconds(int value)
circuitBreaker.errorThresholdPercentage
设置打开回路并启动回退逻辑的错误比率。
默认值:50
默认属性:hystrix.command.default.circuitBreaker.errorThresholdPercentage
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.errorThresholdPercentage
实例默认的设置:HystrixCommandProperties.Setter()
.withCircuitBreakerErrorThresholdPercentage(int value)
circuitBreaker.forceOpen
如果该属性设置为true,强制断路器进入打开状态,将会拒绝所有的请求。
该属性优先级比circuitBreaker.forceClosed高。
默认值:false
默认属性:hystrix.command.default.circuitBreaker.forceOpen
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen
实例默认的设置:HystrixCommandProperties.Setter()
.withCircuitBreakerForceOpen(boolean value)
circuitBreaker.forceClosed
如果该属性设置为true,强制断路器进入关闭状态,将会允许所有的请求,无视错误率。
默认值:false
默认属性:hystrix.command.default.circuitBreaker.forceClosed
实例属性:hystrix.command.HystrixCommandKey.circuitBreaker.forceClosed
实例默认的设置:HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(boolean value)
请求上下文
requestCache.enabled
设置HystrixCommand.getCacheKey()是否启用,由HystrixRequestCache通过请求缓存提供去重复数据功能。
默认值:true
默认属性:hystrix.command.default.requestCache.enabled
实例属性:hystrix.command.HystrixCommandKey.requestCache.enabled
实例默认的设置:HystrixCommandProperties.Setter()
.withRequestCacheEnabled(boolean value)
requestLog.enabled
设置HystrixCommand执行和事件是否要记录日志到HystrixRequestLog。
默认值:true
默认属性:hystrix.command.default.requestLog.enabled
实例属性:hystrix.command.HystrixCommandKey.requestLog.enabled
实例默认的设置:HystrixCommandProperties.Setter()
.withRequestLogEnabled(boolean value)
压缩器属性
下面的属性可以控制HystrixCollapser行为。
maxRequestsInBatch
设置触发批处理执行之前,在批处理中允许的最大请求数。
默认值:Integer.MAX_VALUE
默认属性:hystrix.collapser.default.maxRequestsInBatch
实例属性:hystrix.collapser.HystrixCollapserKey.maxRequestsInBatch
实例默认的设置:HystrixCollapserProperties.Setter()
.withMaxRequestsInBatch(int value)
timerDelayInMilliseconds
设置批处理创建到执行之间的毫秒数。
默认值:10
默认属性:hystrix.collapser.default.timerDelayInMilliseconds
实例属性:hystrix.collapser.HystrixCollapserKey.timerDelayInMilliseconds
实例默认的设置:HystrixCollapserProperties.Setter()
.withTimerDelayInMilliseconds(int value)
requestCache.enabled
设置请求缓存是否对HystrixCollapser.execute()和HystrixCollapser.queue()的调用起作用。
默认值:true
默认属性:hystrix.collapser.default.requestCache.enabled
实例属性:hystrix.collapser.HystrixCollapserKey.requestCache.enabled
实例默认的设置:HystrixCollapserProperties.Setter()
.withRequestCacheEnabled(boolean value)
线程池属性
coreSize
设置核心线程池大小。
默认值:10
默认属性:hystrix.threadpool.default.coreSize
实例属性:hystrix.threadpool.HystrixThreadPoolKey.coreSize
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withCoreSize(int value)
maximumSize
1.5.9新增属性,设置线程池最大值。这个是在不开始拒绝HystrixCommand的情况下支持的最大并发数。这个属性起作用的前提是设置了allowMaximumSizeToDrivergeFromCoreSize。1.5.9之前,核心线程池大小和最大线程池大小总是相同的。
maxQueueSize
设置BlockingQueue最大的队列值。
如果设置为-1,那么使用SynchronousQueue,否则正数将会使用LinkedBlockingQueue。
如果需要去除这些限制,允许队列动态变化,可以参考queueSizeRejectionThreshold属性。
修改SynchronousQueue和LinkedBlockingQueue需要重启。
默认值:-1
默认属性:hystrix.threadpool.default.maxQueueSize
实例属性:hystrix.threadpool.HystrixThreadPoolKey.maxQueueSize
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(int value)
queueSizeRejectionThreshold
设置队列拒绝的阈值——一个人为设置的拒绝访问的最大队列值,即使maxQueueSize还没有达到。
当将一个线程放入队列等待执行时,HystrixCommand使用该属性。
注意:如果maxQueueSize设置为-1,该属性不可用。
默认值:5
默认属性:hystrix.threadpool.default.queueSizeRejectionThreshold
实例属性:hystrix.threadpool.HystrixThreadPoolKey.queueSizeRejectionThreshold
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withQueueSizeRejectionThreshold(int value)
keepAliveTimeMinutes
设置存活时间,单位分钟。如果coreSize小于maximumSize,那么该属性控制一个线程从实用完成到被释放的时间。
默认值:1
默认属性:hystrix.threadpool.default.keepAliveTimeMinutes
实例属性:hystrix.threadpool.HystrixThreadPoolKey.keepAliveTimeMinutes
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withKeepAliveTimeMinutes(int value)
allowMaximumSizeToDivergeFromCoreSize
在1.5.9中新增的属性。该属性允许maximumSize起作用。属性值可以等于或者大于coreSize值,设置coreSize小于maximumSize的线程池能够支持maximumSize的并发数,但是会将不活跃的线程返回到系统中去。(详见KeepAliveTimeMinutes)
默认值:false
默认属性:hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize
实例属性:hystrix.threadpool.HystrixThreadPoolKey.allowMaximumSizeToDivergeFromCoreSize
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withAllowMaximumSizeToDivergeFromCoreSize(boolean value)
metrics.rollingStats.timeInMilliseconds
设置统计的滚动窗口的时间段大小。该属性是线程池保持指标时间长短。
默认值:10000(毫秒)
默认属性:hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds
实例属性:hystrix.threadpool.HystrixThreadPoolKey.metrics.rollingStats.timeInMilliseconds
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withMetricsRollingStatisticalWindowInMilliseconds(int value)
metrics.rollingStats.numBuckets
设置滚动的统计窗口被分成的桶(bucket)的数目。
注意:”metrics.rollingStats.timeInMilliseconds % metrics.rollingStats.numBuckets == 0"必须为true,否则会抛出异常。
默认值:10
可能的值:任何能被metrics.rollingStats.timeInMilliseconds整除的值。
默认属性:hystrix.threadpool.default.metrics.rollingStats.numBuckets
实例属性:hystrix.threadpool.HystrixThreadPoolProperties.metrics.rollingStats.numBuckets
实例默认的设置:HystrixThreadPoolProperties.Setter()
.withMetricsRollingStatisticalWindowBuckets(int value)
网友评论