15.2.2 管理断路器阈值

默认情况下,如果断路器保护的方法被调用超过 20 次,如果超过 50% 的调用在 10 秒钟内失败,那么断路器将进入断开状态。所有后续调用都将由降级方法处理。经过 5 秒后,断路器进入半开状态,原方法将被再次尝试。

您可以通过设置 Hystrix 命令属性来调整失败和重试阈值。以下命令属性会影响断路器:

  • circuitBreaker.requestVolumeThreshold——在给定的时间段内,方法应该被调用的次数。
  • circuitBreaker.errorThresholdPercentage——给定时间段内,失败方法所占的百分比。
  • metrics.rollingStats.timeInMilliseconds——考虑请求量和错误百分比的滚动时间段。
  • circuitBreaker.sleepWindowInMilliseconds——断开状态持续多长时间进入半打开状态,以再次尝试调用原始失败方法。

metrics.rollingState.timeInMilliseconds 中指定的时间段内,如果 circuitBreaker.requestVolumeThresholdcircuitBreaker.errorThresholdPercentage 同时超过阈值,则断路器进入断开状态。在 circuitBreaker.sleepWindowInMilliseconds 指定的时间内保持断开状态。之后将变为半开状态,并再一次尝试最初的失败方法。

例如,假设要调整失败设置,方法的调用次数必须超过 30 次,并且在 20 秒内有超过 25% 的请求失败才触发。需要设置以下 Hystrix 命令属性:

@HystrixCommand(
    fallbackMethod="getDefaultIngredients",
    commandProperties={
        @HystrixProperty(
            name="circuitBreaker.requestVolumeThreshold",
            value="30"),
        @HystrixProperty(
            name="circuitBreaker.errorThresholdPercentage",
            value="25"),
        @HystrixProperty(
            name="metrics.rollingStats.timeInMilliseconds",
            value="20000")
    })
public List<Ingredient> getAllIngredients() {
  // ...
}

此外,如果您决定一旦断开,断路器必须保持断开状态最多 1 分钟,然后转为半开状态,您可以这样设置 circuitBreaker.sleepWindowInMilliseconds 命令属性:

@HystrixCommand(
    fallbackMethod="getDefaultIngredients",
    commandProperties={
        ...
        @HystrixProperty(
            name="circuitBreaker.sleepWindowInMilliseconds",
            value="60000")
    })

除了优雅地处理方法失败和延迟之外,Hystrix 还发布了应用程序中每个断路器的度量流。下一步,让我们看一看如何通过 Hystrix 流,来监控使用 Hystrix 的应用程序的健康状况。

results matching ""

    No results matching ""