• Spring Cloud Hystrix 熔断参数配置


    HystrixCommandProperties命令执行相关配置:

      hystrix.command.[commandkey].execution.isolation.strategy 隔离策略THREAD或SEMAPHORE 默认HystrixCommands使用THREAD方式 HystrixObservableCommands使用SEMAPHORE

      hystrix.command.[commandkey].execution.timeout.enabled 是否开启超时设置,默认true。

      hystrix.command.[commandkey].execution.isolation.thread.timeoutInMilliseconds 默认超时时间 默认1000ms

      hystrix.command.[commandkey].execution.isolation.thread.interruptOnTimeout是否打开超时线程中断 默认值true

      hystrix.command.[commandkey].execution.isolation.thread.interruptOnFutureCancel 当隔离策略为THREAD时,当执行线程执行超时时,是否进行中断处理,即Future#cancel(true)处理,默认为false。

      hystrix.command.[commandkey].execution.isolation.semaphore.maxConcurrentRequests 信号量最大并发度 默认值10该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。 

      hystrix.command.[commandkey].fallback.isolation.semaphore.maxConcurrentRequests fallback方法的信号量配置,配置getFallback方法并发请求的信号量,如果请求超过了并发信号量限制,则不再尝试调用getFallback方法,而是快速失败,默认信号量为10。

      hystrix.command.[commandkey].fallback.enabled 是否启用降级处理,如果启用了,则在超时或异常时调用getFallback进行降级处理,默认开启。

      hystrix.command.[commandkey].circuitBreaker.enabled 是否开启熔断机制,默认为true。

      hystrix.command.[commandkey].circuitBreaker.forceOpen 强制开启熔断,默认为false。

      hystrix.command.[commandkey].circuitBreaker.forceClosed 强制关闭熔断,默认为false。

      hystrix.command.[commandkey].circuitBreaker.sleepWindowInMilliseconds  熔断窗口时间,默认为5s。

      hystrix.command.[commandkey].circuitBreaker.requestVolumeThreshold 当在配置时间窗口内达到此数量后的失败,进行短路。默认20个

      hystrix.command.[commandkey].circuitBreaker.errorThresholdPercentage 出错百分比阈值,当达到此阈值后,开始短路。默认50%

      hystrix.command.[commandkey].metrics.rollingStats.timeInMilliseconds   设置统计滚动窗口的长度,以毫秒为单位。用于监控和熔断器 默认10s

      hystrix.command.[commandkey].metrics.rollingStats.numBuckets  设置统计窗口的桶数量 默认10

      hystrix.command.[commandkey].metrics.rollingPercentile.enabled 设置执行时间是否被跟踪,并且计算各个百分比,50%,90%等的时间 默认true

      hystrix.command.[commandkey].metrics.rollingPercentile.timeInMilliseconds 设置执行时间在滚动窗口中保留时间,用来计算百分比 默认60000ms

      hystrix.command.[commandkey].metrics.rollingPercentile.numBuckets 设置rollingPercentile窗口的桶数量 默认6。

      hystrix.command.[commandkey].metrics.rollingPercentile.bucketSize 此属性设置每个桶保存的执行时间的最大值 默认100。如果bucket size=100,window=10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。

      hystrix.command.[commandkey].metrics.healthSnapshot.intervalInMilliseconds 记录health 快照(用来统计成功和错误绿)的间隔,默认500ms

      hystrix.command.[commandkey].requestCache.enabled 设置是否缓存请求,request-scope内缓存 默认值true

      hystrix.command.[commandkey].requestLog.enabled 设置HystrixCommand执行和事件是否打印到HystrixRequestLog中 默认值true

      hystrix.command.[commandkey].threadPoolKeyOverride   命令的线程池key,决定该命令使用哪个线程池。

    HystrixThreadPoolProperties线程池相关配置:

       hystrix.threadpool.[threadkey].coreSize 线程池核心线程数 默认值10;

      hystrix.threadpool.[threadkey].maximumSize  线程池最大线程数 默认值10; 

      hystrix.threadpool.[threadkey].allowMaximumSizeToDivergeFromCoreSize   当线程数大于核心线程数时,是否需要回收。与keepAliveTimeMinutes配合使用。

      hystrix.threadpool.[threadkey].keepAliveTimeMinutes  当实际线程数超过核心线程数时,线程存活时间 默认值1min

      hystrix.threadpool.[threadkey].maxQueueSize  最大等待队列数 默认不开启使用SynchronousQueue 不可动态调整

      hystrix.threadpool.[threadkey].queueSizeRejectionThreshold   允许在队列中的等待的任务数量 默认值5

      hystrix.threadpool.[threadkey].metrics.rollingStats.timeInMilliseconds 设置统计滚动窗口的长度,以毫秒为单位 默认值10000。

      hystrix.threadpool.[threadkey].metrics.rollingStats.numBuckets 设置统计窗口的桶数量 默认10

     HystrixCollapserProperties批处理相关配置:

      hystrix.collapser.[collapserKey].maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE

      hystrix.collapser.[collapserKey].timerDelayInMilliseconds  触发批处理的延迟,也可以为创建批处理的时间+该值,默认值10

      hystrix.collapser.[collapserKey].requestCache.enabled 默认值true

      hystrix.collapser.[collapserKey].metrics.rollingStats.timeInMilliseconds  默认值10000

      hystrix.collapser.[collapserKey].metrics.rollingStats.numBuckets 默认值10

      hystrix.collapser.[collapserKey].metrics.rollingPercentile.enabled 默认值true

      hystrix.collapser.[collapserKey].metrics.rollingPercentile.timeInMilliseconds 默认值60000

      hystrix.collapser.[collapserKey].metrics.rollingPercentile.numBuckets 默认值6

      hystrix.collapser.[collapserKey].metrics.rollingPercentile.bucketSize 默认值100

    Hystrix常用熔断参数

    1. @HystrixCommand(fallbackMethod = "str_fallbackMethod",
    2. groupKey = "strGroupCommand",
    3. commandKey = "strCommard",
    4. threadPoolKey = "strThreadPool",
    5. commandProperties = {
    6. //设置隔离策略,THREAD表示线程池SEMAPHORE:信号地隔离
    7. @HystrixProperty(name = "execution.isolation. strategy", value = "THREAD"),
    8. //当隔离策略选择信号地隔离的时候,用来没置信号地的大小(最大并发数)
    9. @HystrixProperty(name = "execution.isolation. semaphore.maxConcurrentRequests", value = "10"),
    10. //配置命令执行的超时时间
    11. @HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
    12. //悬否启用超时时间
    13. @HystrixProperty(name = "execution.timeout. enabled", value = "true"),
    14. //执行超时的时候是否中断
    15. @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
    16. //执行被取消的时候是否中断
    17. @HystrixProperty(name = "execution.isolation.thread. interruptOnCancel", value = "true"),
    18. //允许回调方法执行的最大并发数
    19. @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
    20. //服务降级是否启用,是否执行回湖函数
    21. @HystrixProperty(name = "fallback.enabled", value = "true"),
    22. @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
    23. //该属性用来设置在演动时间窗中,断路器熔断的最小请求数。例如,默认该值为20的时候,
    24. //如果滚动时间窗(默认10秒)内仅收到719个请求,即使这19个请求都失败了,断路器也不会打开。
    25. @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
    26. //该属性用来设置在模动时间窗中,表示在滚动时间窗中,在请求数量超过
    27. // circuitBreaker. requestVolumeThreshold的情况下,如果错误请求数的百分比超过50,
    28. //就把断路器设置为“打开"状态,否则就设置为“关闭"状态。
    29. @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
    30. //该属性用来设置当断路器打开之后的休眠时间窗。休眠时间窗结束之后,
    31. //会将断路器置为“半开"状态,尝式熔断的请求命令,如果依然失败就将断路器继续设置为“打开"状态,
    32. //如果成功就设置为“关闭"状态。
    33. @HystrixProperty(name = "circuitBreaker.sleeplindowinMilliseconds", value = "5000"),
    34. //断路器强制打开
    35. @HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
    36. //断路器强制关闭
    37. @HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
    38. //滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
    39. @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
    40. //该属性用来设置凝动时间窗统计指标信息时划分"镑"的数量,断路器在收集指标信息的时候会根据//设置的时间窗长度拆分成多个“裙"来翼计各度量值,每个"裙"记录了一段时间内的采集指标。//比如10秒内拆分成10个“裤”收集这样,所以timeinilliseconds 必须能被numBuckets 整除。 否则会抛异常
    41. @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
    42. //动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
    43. @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
    44. //该属性用来设置模动时间窗统计指标信息时划分"榜"的数量,断路器在收集指标信息的时候会根据
    45. //设置的时间窗长度拆分成多个“裤"来累计各度量值,每个"榜”记录了一段时间内的采集指标。
    46. //比如10秒内拆分成10个"榜"收集这样,所以timeinMilliseconds必须能被numBuckets整除。否则会抛异常
    47. @HystrixProperty(name = "metrics.rollingStats. numBuckets", value = "10"),
    48. //该属性用来设置对命令执行的延迟是否使用百升位数来跟踪和计算。如果设置为false,那么所有的概要统计都将返回-1.
    49. @HystrixProperty(name = "metrics.rollingPercentile. enabled", value = "false"),
    50. //该属性用来设置百分位统计的凝动窗口的持续时间,单位为喜秒。
    51. @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "6000e"),
    52. //该属性用央设置百分位统计模动窗口中使用“榜”的数量
    53. @HystrixProperty(name = "metrics.rollingPercentile. numBuckets", value = "60000"),
    54. //该属性用来设置在执行过程中每个“桶”中保留的最大执行次数。如果在模动时间窗内发生超过该设定值的执行况数,
    55. //就从最初的位置开始重写。例如,将该值设置为100,滚动窗口为10秒,若在10秒内一个“捅”中发生了500次执行
    56. //那么该“桶”中只保留最后的100,次执行的统计。另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
    57. @HystrixProperty(name = "metrics.rollingPercentile. bucketSize", value = "100"),
    58. //该属性用来设置采集影响断路器状态的健康快照(请求的成功、错误百分比)的间隔等待时间。
    59. @HystrixProperty(name = "metrics. healthSnapshot.intervalinMilliseconds", value = "500"),
    60. //悬否开启请求缓存
    61. @HystrixProperty(name = "requestCache. enabled", value = "true"),
    62. // HystrixCommand的执行和事件悬否打印日志到HystrixRequestLog中
    63. @HystrixProperty(name = "requestLog.enabled", value = "true"),
    64. @HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
    65. //该属性用夹设置采集影响断路器状态的健康快照(请求的成功、错误百分比)的间隔等待时间。
    66. @HystrixProperty(name = "metrics. healthSnapshot.intervalinMilliseconds", value = "500"),
    67. //是否开启请求缓存
    68. @HystrixProperty(name = "requestCache.enabled", value = "true"),
    69. // Hystrixcommand的执行和事件是否打印日志到HystrixRequestLog中
    70. @HystrixProperty(name = "requestLog. enabled", value = "true"),
    71. },
    72. threadPoolProperties = {
    73. //该参数用来设置执行命令线程地的核心线程数,该值也就是命令执行的最大并发量
    74. @HystrixProperty(name = "coreSize", value = "10"),
    75. //该参数用来设置线程池的最大队列大小。当没置为-1时,线程池将使用SynchronousQueue实现的队列
    76. //否则将使用LinkedBlockingQueue实现的队列。
    77. @HystrixProperty(name = "maxQueuesize", value = "-1"),
    78. //该参数用来为队列设置拒绝阈值。通过该参数,即使队列没有达到最大值也能拒绝请求。
    79. //该参数主要是对LinkedBlockingQueue队列的补充,因为LinkedBlockingQueue
    80. //队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
    81. @HystrixProperty(name = "queueSizeRejectionThreshold", value = "5")
    82. })
    83. public String paymentInfo_Timeout(Integer id) {
    84. try {
    85. TimeUnit.SECONDS.sleep(1);
    86. } catch (InterruptedException e) {
    87. e.printStackTrace();
    88. }
    89. return "线程池" + Thread.currentThread().getName() + " id" + id;
    90. }

    hystrix执行请求的代码逻辑如下图

     以下为比较重要的hystrix熔断参数。

    1. hystrix:
    2. command:
    3. default:
    4. execution:
    5. isolation:
    6. strategy: THREAD
    7. thread:
    8. timeoutInMilliseconds: 10000
    9. circuitBreaker:
    10. requestVolumeThreshold: 30
    11. sleepWindowInMilliseconds: 5000
    12. errorThresholdPercentage: 90

    strategy指定策略为thread形式,有2种选择分别是SEMAPHORE, THREAD,后者请求执行逻辑在单独线程内执行,前者在当前请求线程内执行。
    timeoutInMilliseconds线程超市时间,我在图里没有画出来。
    errorThresholdPercentage 窗口内请求失败数占比。例如超过90%请求触发失败,才允许打开熔断器。
    requestVolumeThreshold 如果熔断器要触发熔断,当前时间窗口内必须至少有requestVolumeThreshold配置的请求个数。如果errorThresholdPercentage配置了50%,requestVolumeThreshold为1,如果只有进来一个请求,如果请求失败失败,就会立即触发熔断,不合理。
    sleepWindowInMilliseconds熔断触发后,熔断时间。这段时间内都返回fallback结果。
    requestVolumeThresholdsleepWindowInMillisecondserrorThresholdPercentagecircuitBreaker.allowRequest()里被用到。hystrix根据实际请求的状态决定是否允许执行请求。

    1. public boolean allowRequest() {
    2. if (properties.circuitBreakerForceOpen().get()) {
    3. // properties have asked us to force the circuit open so we will allow NO requests
    4. return false;
    5. }
    6. if (properties.circuitBreakerForceClosed().get()) {
    7. // we still want to allow isOpen() to perform it's calculations so we simulate normal behavior
    8. isOpen();
    9. // properties have asked us to ignore errors so we will ignore the results of isOpen and just allow all traffic through
    10. return true;
    11. }
    12. // 熔断器未打开或者熔断时间已经超过熔断时间间隔,则允许请求执行
    13. return !isOpen() || allowSingleTest();
    14. }
    15. public boolean allowSingleTest() {
    16. long timeCircuitOpenedOrWasLastTested = circuitOpenedOrLastTestedTime.get();
    17. // 如果当前熔断器已经打开,并且当前的开启时间已经超过 `sleepWindowInMilliseconds`,则允许请求,并更新`circuitOpenedOrLastTestedTime.compareAndSet`。
    18. // 1) if the circuit is open
    19. // 2) and it's been longer than 'sleepWindow' since we opened the circuit
    20. if (circuitOpen.get() && System.currentTimeMillis() > timeCircuitOpenedOrWasLastTested +
    21. properties.circuitBreakerSleepWindowInMilliseconds().get()) {
    22. // We push the 'circuitOpenedTime' ahead by 'sleepWindow' since we have allowed one request to try.
    23. // If it succeeds the circuit will be closed, otherwise another singleTest will be allowed at the end of the 'sleepWindow'.
    24. if (circuitOpenedOrLastTestedTime.compareAndSet(timeCircuitOpenedOrWasLastTested, System.currentTimeMillis())) {
    25. // if this returns true that means we set the time so we'll return true to allow the singleTest
    26. // if it returned false it means another thread raced us and allowed the singleTest before we did
    27. return true;
    28. }
    29. }
    30. return false;
    31. }
    32. @Override
    33. public boolean isOpen() {
    34. if (circuitOpen.get()) {
    35. // if we're open we immediately return true and don't bother attempting to 'close' ourself as that is left to allowSingleTest and a subsequent successful test to close
    36. return true;
    37. }
    38. // we're closed, so let's see if errors have made us so we should trip the circuit open
    39. HealthCounts health = metrics.getHealthCounts();
    40. // check if we are past the statisticalWindowVolumeThreshold
    41. // 当前窗口请求数未达到 requestVolumeThreshold 数,不打开熔断器
    42. if (health.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) {
    43. // we are not past the minimum volume threshold for the statisticalWindow so we'll return false immediately and not calculate anything
    44. return false;
    45. }
    46. // 当前窗口请求错误占比未达到 errorThresholdPercentage 值,不打开熔断器
    47. if (health.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) {
    48. return false;
    49. } else {
    50. // 打开熔断器
    51. // our failure rate is too high, trip the circuit
    52. if (circuitOpen.compareAndSet(false, true)) {
    53. // if the previousValue was false then we want to set the currentTime
    54. circuitOpenedOrLastTestedTime.set(System.currentTimeMillis());
    55. return true;
    56. } else {
    57. // How could previousValue be true? If another thread was going through this code at the same time a race-condition could have
    58. // caused another thread to set it to true already even though we were in the process of doing the same
    59. // In this case, we know the circuit is open, so let the other thread set the currentTime and report back that the circuit is open
    60. return true;
    61. }
    62. }
    63. }

    除了以上的几个参数外,还有以下几个比较重要的参数。

    1. hystrix:
    2. threadpool:
    3. default:
    4. metrics:
    5. rollingStats:
    6. timeInMilliseconds: 60000
    7. numBuckets: 1

    timeInMilliseconds 表示窗口的时间范围,numBuckets表示桶数量,每个桶的时间为timeInMilliseconds/numBuckets,hystrix统计桶时间内错误数和错误比例来决定是否熔断。

  • 相关阅读:
    实现α-β剪枝的算法实例
    AI遮天传 ML-广义线性模型(一)
    原生js预览ofd文件
    数据库 设计规范数据库设计样例
    什么是Web3?去中心化的互联网如何颠覆数字经济
    原型链中:为什么Function.proto==Function.prototype?
    Delphi 的操作符重载 - Record 结构体
    【论文解读】Performance Comparison of H.264 and H.265 Encoders for 4K Video Sequences
    LogUtils工具类
    Win11怎么调亮度?Win11调屏幕亮度的四种方法
  • 原文地址:https://blog.csdn.net/WXF_Sir/article/details/126365895