Loading

Feign实现服务熔断

SpringCloud Fegin默认已为Feign整合了hystrix,所以添加Feign依赖后就不用在添加hystrix,那么怎么才能让Feign的熔断机制生效呢,只要按以下步骤开发:

(1)复制 shop_service_order 项目并命名为 shop_service_order_feign_hystrix

(2)修改application.yml在Fegin中开启hystrix

在Feign中已经内置了hystrix,但是默认是关闭的需要在工程的 application.yml 中开启对hystrix的支持
  feign:
    hystrix: #在feign中开启hystrix熔断
      enabled: true

(3)配置FeignClient接口的实现类

基于Feign实现熔断降级,那么降级方法需要配置到FeignClient接口的实现类中
/**
*  实现自定义的ProductFeginClient接口
*      在接口实现类中编写熔断降级方法
*/
@Component
public class ProductFeginClientCallBack implements ProductFeginClient {

  /**
   * 降级方法
   */
  public Product findById(Long id) {
      Product product = new Product();
      product.setId(-1l);
      product.setProductName("熔断:触发降级方法");
      return product;
  }
}

(4)修改FeignClient添加hystrix熔断

在@FeignClient注解中添加降级方法
//指定需要调用的微服务名称
@FeignClient(name="shop-service-product",fallback =
ProductFeginClientCallBack.class)
public interface ProductFeginClient {

  //调用的请求路径
  @RequestMapping(value = "/product/{id}",method = RequestMethod.GET)
  public Product findById(@PathVariable("id") Long id);
}
@FeignClient注解中以fallback声明降级方法
posted @ 2021-07-27 16:59  1640808365  阅读(1169)  评论(0编辑  收藏  举报