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聲明降級方法