前言
上一篇我們使用注解@HystrixCommond的fallbackMethod屬性實現回退。然而,Feign是以接口形式工作的,它沒有方法體,上一篇講解的方式顯然不適用於Feign。
那么Feign要如何整合Hystrix呢?不僅如此,如何實現Feign的回退。
在springcloud中,為Feign添加回退更加簡單。事實上,springcloud默認已為Feign整合了Hystrix,要想為Feign打開Hystrix支持,只需要設置feign.hystrix.enabled=true即可。
編碼
1.復制項目microservie-consumer-movie-feign,將ArtifactId修改為microservice-consumer-movie-feign-hystrix-fallback.
2.在application.yml中添加feign.hystrix.enabled: true,從而開啟Feign的Hystrix支持。
server: port: 8082 eureka: client: serviceUrl: defaultZone: http://localhost:8083/eureka/ instance: prefer-ip-address: true spring: application: name: microservice-consumer-movie feign: hystrix: enabled: true
3.將之前編寫的Feign接口修改成如下內容:
@FeignClient(name = "microservice-provider-user",fallback = FeignClientFallback.class) public interface UserFeignClient { @RequestMapping(value="/{id}",method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); } @Component class FeignClientFallback implements UserFeignClient{ public User findById(Long id) { User user = new User(); user.setId(-1L); user.setUsername("默認用戶"); return user; } }
由代碼可知,只需使用@FeignClient注解的fallback屬性,就可為指定名稱的Feign客戶添加回退。
測試
啟動microservice-discovery-eureka.
啟動microservice-provider-user.
啟動microservice-consumer-movie-feign-hystrix-fallback.
訪問http://localhost:8082/user/1,可正常獲得結果。
{"id":1,"username":"account1","name":"張三","age":20,"balance":98.23}
停止microservice-provider-user.
再次訪問http://localhost:8082/user/1,可獲得如下結果。說明當用戶微服務不可用時,進入了回退的邏輯。
{"id":-1,"username":"默認用戶","name":null,"age":null,"balance":null}
補充:在springcloud Dalston之前的版本中,Feign默認開啟Hystrix支持,無需設置feign.hystrix.enabled=true.從springcloud Dalston版本開始,Feign的Hystrix支持默認關閉,需要手動設置開啟。
由於代碼過於簡單,這里就不提交源碼了。