Feign整合Hystrix实现容错处理
开启Feign对Hystrix的支持,需要在配置文件中增加如下代码:
#开启Hystrix
feign:
hystrix:
enabled: true
Feign对Hystrix的容错处理支持两种方式,一种Fallback ,另一种FallbackFactory 方式。
FallbackFactory 和 Fallback 的区别只是能捕获到调用异常。
Fallback 方式
- 在FeignClient注解中使用fallback 指定熔断回退处理类,此类需要实现FeignClient注解得了类。
@FeignClient(value = "user-server",fallback = FeignUserServiceHystrix.class)
public interface FeignUserService {
@GetMapping("user")
public String user(@RequestParam(value = "name") String name);
}
- 创建FeignUserServiceHystrix熔断回退处理类,要求此类必须实现FeignUserService 接口,当网络不同或者其他问题导致的访问失败,则执行实现方法中处理逻辑。
@Component
public class FeignUserServiceHystrix implements FeignUserService {
@Override
public String user(@RequestParam(value = "name") String name) {
return "sorry "+name+",user has fail!";
}
}
FallbackFactory方式
- 在FeignClient注解中使用fallbackFactory 指定熔断回退处理类,此类需要实现FallbackFactory。
@FeignClient(value = "product-server",fallbackFactory = FeignProductServiceHystrix.class)
public interface FeignProductService {
@GetMapping("hello")
public String hello(@RequestParam(value = "name") String name);
}
- 创建FeignProductServiceHystrix熔断回退处理类,要求此类必须实现FallbackFactory接口,当网络不同或者其他问题导致的访问失败,打印异常日志并通过匿名内部类进行回退处理。
@Component
@Slf4j
public class FeignProductServiceHystrix implements FallbackFactory<FeignProductService> {
@Override
public FeignProductService create(Throwable throwable) {
log.error("FeignProductService回退:", throwable);
return new FeignProductService() {
@Override
public String hello(String name) {
return "sorry "+name+",product has fail!";
}
};
}
}