多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
OpenFeign用来处理异常有如下两种方式: ```java public @interface FeignClient { ... // 1. 使用fallback。【服务降级演示】小节用的就是fallback Class<?> fallback() default void.class; // 2. 使用fallbackFactory Class<?> fallbackFactory() default void.class; ... } ``` <br/> 下面介绍使用`fallbackFactory`进行降级处理。步骤如下: **1. 封装Feign接口用来访问服务端** ```java /** * fallbackFactory:指定异常处理类,PaymentHystrixService接口的某一个方法发生异常时 * 就会去调用fallbackFactory类里面对应的方法。 */ @Component @FeignClient(value = "${provider.payment.name}", fallbackFactory = PaymentHystrixServiceFallbackFactory.class) public interface PaymentHystrixService { @GetMapping("/payment/hystrix/circuit/{id}") String paymentCircuitBreaker(@PathVariable("id") Integer id); } ``` **2. 封装异常处理类`PaymentHystrixServiceFallbackFactory`** ``` @Slf4j @Component public class PaymentHystrixServiceFallbackFactory implements FallbackFactory<PaymentHystrixService> { @Override public PaymentHystrixService create(Throwable throwable) { return new PaymentHystrixService() { /** * 当方法 PaymentHystrixService.paymentCircuitBreaker发生异常时就会自动调用该方法 * 做后续处理。 */ @Override public String paymentCircuitBreaker(Integer id) { String info = "paymentCircuitBreaker is exception!,e=" + throwable.getMessage(); log.warn(info); return info; } }; } } ``` **3. 测试** 将服务端关闭,就会得到如下的响应。http://localhost/order/hystrix/circuit/10 ```json paymentCircuitBreaker is exception!,e=null ```