19

在 Spring Boot 应用程序中使用注释时,有没有办法获取HystrixCommand失败的原因?@HystrixCommand看起来如果您实现自己的HystrixCommand,则可以访问,getFailedExecutionException但是在使用注释时如何访问呢?我希望能够根据发生的异常类型在回退方法中做不同的事情。这可能吗?

我看到了一个关于但不让你访问任何东西的注释,是否有不同的方法来使用该上下文来访问异常HystrixRequestContext.initializeContext()HystrixRequestContext

4

5 回答 5

52

只需将 Throwable 参数添加到回退方法,它将接收原始命令产生的异常。

来自https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica

    @HystrixCommand(fallbackMethod = "fallback1")
    User getUserById(String id) {
        throw new RuntimeException("getUserById command failed");
    }

    @HystrixCommand(fallbackMethod = "fallback2")
    User fallback1(String id, Throwable e) {
        assert "getUserById command failed".equals(e.getMessage());
        throw new RuntimeException("fallback1 failed");
    }
于 2016-03-07T02:04:39.870 回答
19

我也没有找到使用注释获取异常的方法,但是创建自己的命令对我有用,如下所示:

public static class DemoCommand extends HystrixCommand<String> {

    protected DemoCommand() {
        super(HystrixCommandGroupKey.Factory.asKey("Demo"));
    }

    @Override
    protected String run() throws Exception {
        throw new RuntimeException("failed!");
    }

    @Override
    protected String getFallback() {
        System.out.println("Events (so far) in Fallback: " + getExecutionEvents());
        return getFailedExecutionException().getMessage();
    }

}

希望这对其他人也有帮助。

于 2015-09-29T16:15:10.143 回答
4

正如文档中所说,Hystrix-documentation getFallback()方法将在以下情况下被抛出:

  1. 每当命令执行失败时:construct() 或 run() 抛出异常时
  2. 当命令因为电路开路而短路时
  3. 当命令的线程池和队列或信号量已满时
  4. 当命令超过其超时长度时。

因此,您可以通过将执行异常分配给Throwable 对象轻松获取引发您调用的回退方法的原因。

假设您的 HystrixCommand 返回一个字符串

public class ExampleTask extends HystrixCommand<String> {
   //Your class body
}

执行以下操作:

@Override
    protected ErrorCodes getFallback() {
        Throwable t = getExecutionException();
        if (circuitBreaker.isOpen()) {
            // Log or something
        } else if (t instanceof RejectedExecutionException) {
            // Log and get the threadpool name, could be useful
        } else {
            // Maybe something else happened
        }
        return "A default String"; // Avoid using any HTTP request or ypu will need to wrap it also in HystrixCommand
    }

更多信息在这里

于 2018-06-20T02:12:15.493 回答
3

我找不到使用注释获取异常的方法,但我发现HystrixPlugins,您可以注册 aHystrixCommandExecutionHook并且您可以像这样获得确切的异常:

HystrixPlugins.getInstance().registerCommandExecutionHook(new HystrixCommandExecutionHook() {
            @Override
            public <T> void onFallbackStart(final HystrixInvokable<T> commandInstance) {

            }
        });

命令实例是一个GenericCommand.

于 2015-09-29T12:29:08.483 回答
3

大多数时候,只是使用 getFailedExecutionException().getMessage() 给了我空值。

   Exception errorFromThrowable = getExceptionFromThrowable(getExecutionException());
   String errMessage = (errorFromThrowable != null) ? errorFromThrowable.getMessage()

这一直给我更好的结果。

于 2016-12-01T14:51:49.947 回答