Spring Cloud中,Feign常見問題的總結。
FeignClient介面,不能使用@GettingMapping 之類的組合註解
程式碼示例:

這邊的@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) 不能寫成@GetMapping("/simple/{id}") 。
FeignClient介面中,如果使用到@PathVariable ,必須指定其value
程式碼示例:

這邊的@PathVariable("id") 中的”id”,不能省略,必須指定。
FeignClient多引數的構造
如果想要請求microservice-provider-user 服務,並且引數有多個例如:http://microservice-provider-user/query-by?id=1&username=張三 要怎麼辦呢?
直接使用複雜物件:

該請求不會成功,只要引數是複雜物件,即使指定了是GET方法,feign依然會以POST方法進行傳送請求。
正確的寫法:
寫法1:

寫法2:

Feign如果想要使用Hystrix Stream,需要做一些額外操作
我們知道Feign本身就是支援Hystrix的,可以直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class) 來指定fallback的類,這個fallback類整合@FeignClient所標註的介面即可。
但是假設我們需要使用Hystrix Stream進行監控,預設情況下,訪問http://IP:PORT/hystrix.stream 是個404。如何為Feign增加Hystrix Stream支援呢?
需要以下兩步:
第一步:新增依賴,示例:

第二步:在啟動類上新增@EnableCircuitBreaker 註解,示例:

這樣修改以後,訪問任意的API後,再訪問http://IP:PORT/hystrix.stream,就會展示出一大堆的API監控資料了。
如果需要自定義單個Feign配置,Feign的@Configuration 註解的類不能與@ComponentScan 的包重疊
如果包重疊,將會導致所有的Feign Client都會使用該配置。
首次請求失敗
@FeignClient 的屬性注意點
(1) serviceId屬性已經失效,儘量使用name屬性。例如:

這麼寫是不推薦的,應寫為:

(2) 在使用url屬性時,在老版本的Spring Cloud中,不需要提供name屬性,但是在新版本(例如Brixton、Camden)@FeignClient必須提供name屬性,並且name、url屬性支援佔位符。例如:

歡迎大家和我一起學習spring cloud構建微服務雲架構,我這邊會將近期研發的spring cloud微服務雲架構的搭建過程和精髓記錄下來,幫助更多有興趣研發spring cloud框架的朋友,大家來一起探討spring cloud架構的搭建過程及如何運用於企業專案。
我本人邀約各大BATJ架構大牛共創Spring Cloud構建微服務架構的交流社群。 (群號:547793198)歡迎各路架構師、開發者,學習與交流使用Spring Cloud諸多強大元件的實戰經驗。
為什麼某些人會一直比你優秀,是因為他本身就很優秀還一直在持續努力變得更優秀,而你是不是還在滿足於現狀內心在竊喜!
合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!
希望此文能幫到大家的同時,也聽聽大家的觀點。歡迎留言討論,加關注,分享你的高見!持續更新!
- To-陌霖Java架構
分享網際網路最新文章 關注網際網路最新發展