21

Hystrix降级逻辑中如何获取触发的异常

 5 years ago
source link: http://blog.didispace.com/hystrix-fallback-cause-exception/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

通过之前Spring Cloud系列教程中的 《Spring Cloud构建微服务架构:服务容错保护(Hystrix服务降级)》 一文,我们已经知道如何通过Hystrix来保护自己的服务不被外部依赖方拖垮的情况。但是实际使用过程中经常碰到开发反应“莫名”触发了降级逻辑的情况。为了更精准的定位触发原因,或是在降级逻辑中需要根据不同的异常做不同的处理时,在降级方法中,我们希望可以获取到主逻辑中抛出的异常信息。接下来就来介绍一下Hystrix两种不同实现方式中如何在降级逻辑中获取异常信息的方法。

注解方式

先介绍一下用注解方式定义的Hystrix命令是如何在降级逻辑中获取异常的,实现非常简单,先看下面的例子:

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

User fallback(String id, Throwable throwable) {
    return new User("def", "def");
}

这里定义了一个主逻辑函数 getUserById ,主逻辑中会主动抛出一个异常,从而触发该主逻辑的降级函数 fallback 。重点看 fallback 函数中的最后一个传参 Throwable throwable 。通过这样的简单定义,开发人员就可以很方便的获取触发降级逻辑的异常信息,用作日志记录或者其它复杂的业务逻辑了。

继承方式

在继承方式中要获取触发异常也非常简单,具体如下:

public static class UserCommand extends HystrixCommand<User> {

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

    @Override
    protected User run() throws Exception {
        throw new RuntimeException("getUserById command failed");
    }

    @Override
    protected User getFallback() {
        System.out.println(getFailedExecutionException().getMessage());
        return new User("def", "def");
    }

}

上面的实现同上一节注解方式的实现一样,在使用继承方式的时候通过 getFailedExecutionException 方法就可以获取到触发降级的异常信息了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK