Hystrix支持后备方案(fallback)的概念: 电路断开(也就是不通电时)或者遇到错误时执行一段缺省代码。要对一个给定的@FeignClient启用后备方案,将它的fallback属性设置成后备方案逻辑实现类的类名。如下所示 :
@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
static class HystrixClientFallback implements HystrixClient {
@Override
public Hello iFailSometimes() {
return new Hello("fallback");
}
}
如果你需要知道后备方案逻辑被触发的原因,那就得使用@FeignClient的属性fallbackFactory。如下所示 :
@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}
注意 : 目前在
Feign使用Hystrix后备逻辑机制还有一定的限制: 对于返回com.netflix.hystrix.HystrixCommand和rx.Observable的方法,还不支持后备方案(fallback)。
513

被折叠的 条评论
为什么被折叠?



