企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
在消费端 cloud-comsumer-feign-hystrix-order80 进行演示。 <br/> 步骤如下: **1. 封装Feign接口用来访问服务端** ```java /** * fallback:指定异常处理类,PaymentHystrixService接口的某一个方法发生异常时 * 就会去调用fallback类里面对应的方法。 */ @Component @FeignClient(value = "${provider.payment.name}", fallback = PaymentHystrixServiceFallback.class) public interface PaymentHystrixService { @GetMapping("/payment/hystrix/circuit/{id}") String paymentCircuitBreaker(@PathVariable("id") Integer id); } ``` **2. 封装异常处理类`PaymentHystrixServiceFallback`** ```java @Slf4j @Component public class PaymentHystrixServiceFallback implements PaymentHystrixService { /** * 当方法 PaymentHystrixService.paymentCircuitBreaker发生异常时就会自动调用该方法 * 做后续处理。 */ @Override public String paymentCircuitBreaker(Integer id) { String info = "paymentCircuitBreaker is exception!"; log.warn(info); return info; } } ``` **3. controller层** ```java @RestController @RequestMapping("/payment") public class PaymentController { @Resource private PaymentService paymentService; @GetMapping("/hystrix/circuit/{id}") public String paymentCircuitBreaker(@PathVariable("id") Integer id) { String res = paymentService.paymentCircuitBreaker(id); return res; } } ``` **4. 测试** (1)启动2个Eureka注册中心。 ``` cloud-eureka-server7001 cloud-eureka-server7002 ``` (2)启动服务端和客户端。 ``` cloud-provider-hystrix-payment8001 cloud-comsumer-feign-hystrix-order80 ``` (3)服务端正常,就会得到正常的响应。http://localhost/order/hystrix/circuit/10 ```json hystrix-PaymentServiceImpl-1,成功调用,流水号是:ff2a715e779e4cd68be299b1a17c9ef5 ``` (4)将服务端关闭,就会得到如下的响应。http://localhost/order/hystrix/circuit/10 ```json paymentCircuitBreaker is exception! ``` <br/> 可见,当服务端关闭后,消费端调用了方法`PaymentHystrixServiceFallback.paymentCircuitBreaker`进行异常处理。 这样做就是告诉客户端,这个服务暂时关闭了,请到其它服务端获取服务,不要在我这边等待了,避免不必要的资源浪费和拥堵。