SpringCloud系列(33)--使用Hystrix进行通配服务降级
前言:在上一节中我们使用Hystrix进行了全局服务降级,但服务降级用的相关代码都写在了controller层中,与业务代码高度耦合了,所以本节内容则是关于如何使服务降级的相关代码与业务代码解耦。
1、在cloud-consumer-feign-hystrix-order80子模块下的service包下新建一个名为PaymentFallbackService的类
效果图:
2、修改cloud-consumer-feign-hystrix-order80子模块的PaymentFallbackService类
package com.ken.springcloud.service;import org.springframework.stereotype.Component;@Component
public class PaymentFallbackService implements PaymentHystrixService{@Overridepublic String paymentInfoOK(Integer id) {return "PaymentFallbackService fall back paymentInfoOK";}@Overridepublic String paymentInfoTimeOut(Integer id) {return "PaymentFallbackService fall back paymentInfoTimeOut";}}
3、修改cloud-consumer-feign-hystrix-order80子模块的PaymentHystrixService类
package com.ken.springcloud.service;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@Component
//这里@FeignClient里写的是指定要访问的微服务的名称,表示通过FeignClient去Eureka上面找名称为CLOUD-PROVIDER-HYSTRIX-PAYMENT的微服务的接口,PaymentFallbackService是负责服务降级处理的类,统一为当前接口的方法进行异常处理
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {//指明要调用的CLOUD-PROVIDER-HYSTRIX-PAYMENT的微服务的接口,这里调用的是PaymentController类里的/payment/hystrix/ok/{id}接口@GetMapping("/payment/hystrix/ok/{id}")public String paymentInfoOK(@PathVariable("id") Integer id);//指明要调用的CLOUD-PROVIDER-HYSTRIX-PAYMENT的微服务的接口,这里调用的是PaymentController类里的/payment/hystrix/timeout/{id}接口@GetMapping("/payment/hystrix/timeout/{id}")public String paymentInfoTimeOut(@PathVariable("id") Integer id);}
4、重启cloud-consumer-feign-hystrix-order80服务
效果图:
5、 在浏览器的地址栏里输入http://localhost:8080/consumer/payment/hystrix/ok/1通过调用这个接口查看服务消费者的全局服务降级功能是否正常运行
由图可知cloud-consumer-feign-hystrix-order80服务和cloud-provider-hystrix-payment8001正常运行
6、关停cloud-provider-hystrix-payment8001服务,然后重新在浏览器的地址栏里输入http://localhost:8080/consumer/payment/hystrix/ok/1通过调用这个接口查看在服务提供者宕机的情况下服务消费者的服务降级功能是否正常运行
效果图:
由图可知服务消费者在服务提供者宕机后走了PaymentFallbackService类的服务降级处理,让服务消费者在服务提供者不可用后也可以获取到提示信息从而使得服务消费者不会挂起、重试来占用资源从而耗死服务器