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接口实现类,目的就是在实现类中书写熔断降级方法。

package com.neusoft.feign;

import org.springframework.stereotype.Component;
import com.neusoft.po.CommonResult;

@Component
public class FoodFeignClientCallBack implements FoodFeignClient{

    @Override
    public CommonResult listFoodByBusinessId(Integer businessId) {
        //返回降级响应(食品信息返回null)
        return new CommonResult(403,"fegin触发了熔断降级",null);
    }
}

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

1.4.修改FeignClient接口配置

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

//@FeignClient注解的fallback属性指定熔断降级方法
@FeignClient(name="food-server",fallback=FoodFeignClientCallBack.class)
public interface FoodFeignClient {

    @GetMapping("/FoodController/listFoodByBusinessId/{businessId}")
    public CommonResult listFoodByBusinessId(@PathVariable("businessId") Integer businessId);
}

1.5.修改Controller控制器

修改business_server_10300工程中的BusinessController控制器

@CrossOrigin("*")
@RestController
@RequestMapping("/BusinessController")
public class BusinessController {

    @Autowired
    private BusinessService businessService;
    @Autowired
    private FoodFeignClient foodFeignClient;

    @GetMapping("/listBusinessByOrderTypeId/{orderTypeId}")
    public CommonResult<List> listBusinessByOrderTypeId(@PathVariable("orderTypeId") Integer orderTypeId)
            throws Exception {
        List<Business> list = businessService.listBusinessByOrderTypeId(orderTypeId);
        return new CommonResult(200, "success", list);
    }

    @GetMapping("/getBusinessById/{businessId}")
    public CommonResult<Business> getBusinessById(@PathVariable("businessId") Integer businessId) throws Exception {
        Business business = businessService.getBusinessById(businessId);
        //在商家微服务中调用食品微服务
        CommonResult<List> result = foodFeignClient.listFoodByBusinessId(businessId);
        //如果食品微服务返回降级响应,那么就返回空集合
        if (result.getCode() == 200) {
            business.setFoodList(result.getResult());
        }else {
            business.setFoodList(new ArrayList());
        }
        return new CommonResult(200, "success", business);
    }
}

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

1.6.测试

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

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