Spring Cloud中關於Feign的常見問題
轉載:自指令碼之家:https://www.jb51.net/article/106950.htm
一、FeignClient介面,不能使用@GettingMapping 之類的組合註解
程式碼示例:
1 2 3 4 5 6 |
@PathVariable ( "id" ) Long id);
|
這邊的@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
不能寫成@GetMapping("/simple/{id}")
。
二、FeignClient介面中,如果使用到@PathVariable ,必須指定其value
程式碼示例:
1 2 3 4 5 6 |
|
這邊的@PathVariable("id")
中的”id”,不能省略,必須指定。
三、FeignClient多引數的構造
如果想要請求microservice-provider-user 服務,並且引數有多個例如:http://microservice-provider-user/query-by?id=1&username=張三 要怎麼辦呢?
直接使用複雜物件:
1 2 3 4 5 6 |
|
該請求不會成功,只要引數是複雜物件,即使指定了是GET方法,feign依然會以POST方法進行傳送請求。
正確的寫法:
寫法1:
1 2 3 4 5 |
|
寫法2:
1 2 3 4 5 |
|
四、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支援呢?
需要以下兩步:
第一步:新增依賴,示例:
1 2 3 4 5 |
|
第二步:在啟動類上新增@EnableCircuitBreaker 註解,示例:
1 2 3 4 5 6 7 8 9 |
|
這樣修改以後,訪問任意的API後,再訪問http://IP:PORT/hystrix.stream,就會展示出一大堆的API監控資料了。
五、如果需要自定義單個Feign配置,Feign的@Configuration 註解的類不能與@ComponentScan 的包重疊
如果包重疊,將會導致所有的Feign Client都會使用該配置。
六、首次請求失敗
詳見:解決Spring Cloud中Feign/Ribbon第一次請求失敗的方法
七、@FeignClient 的屬性注意點
(1) serviceId屬性已經失效,儘量使用name屬性。例如:
1 |
|
這麼寫是不推薦的,應寫為:
1 |
|
(2) 在使用url屬性時,在老版本的Spring Cloud中,不需要提供name屬性,但是在新版本(例如Brixton、Camden)@FeignClient必須提供name屬性,並且name、url屬性支援佔位符。例如:
1 |
|