Spring Cloud Feign 声明式服务调用的fallback接口获取异常信息

常规fallback实现

一般情况下,我们为feign客户端定义fallback是下边方式:


// feign接口
@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

// feign降级
static class HystrixClientFallback implements HystrixClient {
    @Override
    public Hello iFailSometimes() {
        return new Hello("fallback");
    }
}

从上边的代码中可以看到,在fallback实现类中没有获取异常信息参数,在实际开发中往往需要获取异常信息,下边是获取异常信息的实现方法:

// feign接口
@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

// feign降级
@Component
static class HystrixClientFallbackFactory implements FallbackFactory {
    @Override
    public HystrixClient create(Throwable cause) {
        return new HystrixClient() {
            @Override
            public Hello iFailSometimes() {
                return new Hello("fallback; reason was: " + cause.getMessage());
            }
        };
    }
}

从上边的代码中可以看到在@FeignClient注解上使用fallbackFactory属性设置fallback实现类,然后实现FallbackFactory<>接口,它的create方法携带了异常信息参数,并在里边返回我们自定义的feign客户端接口,在实现类中调用create的参数即可获取异常信息

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章