1.添加Hystrix熔断降级

本阶段项目完成总架构图中的第四阶段,添加商家微服务(服务消费者)的Hystrix熔断降级处理。
elm.png
本阶段只实现商家微服务调用食品微服务的熔断降级处理,其它微服务的熔断降级处理,放在Getaway网关中实现。

1.1.导入Hystrix依赖

SpringCloud默认已为Feign整合了hystrix,所以添加Feign依赖后就不用在添加hystrix依赖了(可以看到依赖中已经有了feign-hystrix-x.jar文件,也可以在feign依赖中追查到hystrix依赖)。

1.2.在Fegin中开启hystrix

修改business_server_10300工程的application.yml文件,开启hystrix熔断机制

  1. feign:
  2. hystrix:
  3. enabled: true #在feign中开启hystrix熔断机制

1.3.创建FeignClient接口实现类

在business_server_10300工程中创建FeignClient接口实现类,目的就是在实现类中书写熔断降级方法。

  1. package com.neusoft.feign;
  2. import org.springframework.stereotype.Component;
  3. import com.neusoft.po.CommonResult;
  4. @Component
  5. public class FoodFeignClientCallBack implements FoodFeignClient{
  6. @Override
  7. public CommonResult listFoodByBusinessId(Integer businessId) {
  8. //返回降级响应(食品信息返回null)
  9. return new CommonResult(403,"fegin触发了熔断降级",null);
  10. }
  11. }

注意:要使用@Component注解将此实现类实例放入Spring容器中。

1.4.修改FeignClient接口配置

在FeignClient接口中,配置熔断发生时要调用的降级方法

  1. //@FeignClient注解的fallback属性指定熔断降级方法
  2. @FeignClient(name="food-server",fallback=FoodFeignClientCallBack.class)
  3. public interface FoodFeignClient {
  4. @GetMapping("/FoodController/listFoodByBusinessId/{businessId}")
  5. public CommonResult listFoodByBusinessId(@PathVariable("businessId") Integer businessId);
  6. }

1.5.修改Controller控制器

修改business_server_10300工程中的BusinessController控制器

  1. @CrossOrigin("*")
  2. @RestController
  3. @RequestMapping("/BusinessController")
  4. public class BusinessController {
  5. @Autowired
  6. private BusinessService businessService;
  7. @Autowired
  8. private FoodFeignClient foodFeignClient;
  9. @GetMapping("/listBusinessByOrderTypeId/{orderTypeId}")
  10. public CommonResult<List> listBusinessByOrderTypeId(@PathVariable("orderTypeId") Integer orderTypeId)
  11. throws Exception {
  12. List<Business> list = businessService.listBusinessByOrderTypeId(orderTypeId);
  13. return new CommonResult(200, "success", list);
  14. }
  15. @GetMapping("/getBusinessById/{businessId}")
  16. public CommonResult<Business> getBusinessById(@PathVariable("businessId") Integer businessId) throws Exception {
  17. Business business = businessService.getBusinessById(businessId);
  18. //在商家微服务中调用食品微服务
  19. CommonResult<List> result = foodFeignClient.listFoodByBusinessId(businessId);
  20. //如果食品微服务返回降级响应,那么就返回空集合
  21. if (result.getCode() == 200) {
  22. business.setFoodList(result.getResult());
  23. }else {
  24. business.setFoodList(new ArrayList());
  25. }
  26. return new CommonResult(200, "success", business);
  27. }
  28. }

添加熔断降级的判断处理。

1.6.测试

停止食品微服务(服务提供者: food_server_10200、food_server_10201),也就是模拟服务提供者宕机。

此时,当访问商家微服务时,就会看到:当食品微服务出现问题之后,商家微服务仍然可以正常响应,只是食品信息为null,这就是熔断降级处理后的效果。