Hystrix Fallback 方法执行

Hystrix Fallback method execution

下面是我的 Hystrix 命令配置:

@HystrixCommand(fallbackMethod = "fall", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000") })
    public <T> T getInfo(Class clazz) {....}

后备方法:

public <T> T fall(Class clazz) {
        System.out.println("fallback");
        throw new CustomRuntimeException("API Down"); 
    }

我了解按照以下配置即

@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000") }

5 个请求将在 10 秒内被允许,直到电路跳闸打开,第 5 个请求的每个请求都将被拒绝,因为我在回退方法中抛出异常,它将被包装为 HystrixRuntimeException.

但我面临以下问题:

问题:

  1. 为什么在电路打开之前异常没有被包装为 HystrixRuntimeException 即当前回退正常执行并抛出 CustomRuntimeException 直到电路打开?*

  1. 为什么在流程1->2->3->4->5->6->8中fallback方法执行完了 失败(即抛出 CustomRuntimeException)并且不抛出 包裹HystrixRuntimeException,这是在流的情况下发生的 1->2->3->4->8 和 1->2->3->5->8

异常处理请参考Hystrix Javanica文档:https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#error-propagation

引用文档:

"It is worth noting that by default a caller will always get the root cause exception ... never HystrixBadRequestException or HystrixRuntimeException"

"If command has a fallback then only first exception that triggers fallback logic will be propagated to caller."

这两句话回答了你的第一个问题:第一个方法的异常将是抛出的异常,而不是 HystrixRuntimeException。永远不会显示回退中抛出的异常。

断路器打开时,将抛出RuntimeException。同样,回退中抛出的异常将永远不会显示。

我为此写了一个测试用例:https://github.com/ahus1/hystrix-spring-examples/blob/master/src/test/java/de/ahus1/hystrixspring/HystrixExceptionHandlingInSpring.java

旁注:

  1. 您已将电路断路器的配置添加到代码中。它们通常最好放在 spring 配置中,其全名是:hystrix.command.default.circuitBreaker.requestVolumeThreshold.

  2. requestVolumeThreshold 的工作方式与您描述的略有不同:它定义了允许触发 cicruit 断路器之前 window 时间内所需的最小请求数。 errorThresholdPercentage 是达到最小请求数(在您的情况下为 5)后允许的错误百分比。在您的情况下,5 个呼叫中有 5 个失败,即 100%。 100% 大于 50%(断路器默认值),因此打开。