SpringCloud Feign引數問題及解決方法
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了SpringCloud Feign引數問題及解決方法,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
今天遇到使用Feign呼叫微服務,傳遞引數時遇到幾個問題
1.無引數
以GET方式請求
服務提供者
@RequestMapping("/hello") public String Hello(){ return "hello,provider"; }
服務消費者
@GetMapping("/hello") String hello();
2.單個引數
(1)GET——@PathVariable
服務提供者
@GetMapping("/test/{name}") public String test(@PathVariable String name){ return "hello,"+name; }
服務消費者
@GetMapping("/test/{name}") String test(@PathVariable("name") String name);
(2)GET——@RequestParam
服務提供者
@RequestMapping("/test") public String test(String name){return "hello,"+name; }
服務消費者
@RequestMapping("/test") String test(@RequestParam String name);
會遇到報錯
RequestParam.value() was empty on parameter 0
解決方法:
加上註解的描述,修改為
@RequestMapping("/test") String test(@RequestParam("name") String name);
(3)POST
@RequestBody
不需要註解的描述
@RequestMapping("/test") String test(@RequestBody String name);
注:
- 引數前使用了@RequestBody註解的,都以POST方式消費服務
- @RequestBody註解的引數,需要POST方式才能傳遞資料
2.Feign多引數的問題
(1)GET——@PathVariable
服務提供者
@GetMapping("/test/{name}/{xyz}") public String test(@PathVariable String name,@PathVariable String xyz){ return "hello,"+name+","+xyz; }
服務消費者
@GetMapping("/test/{name}/{xyz}") String test(@PathVariable("name") String name,@PathVariable("xyz") String xyz);
(1)GET——@RequestParam
服務提供者
@RequestMapping("/test") public String test(String name,Integer type){ if(type==1){ return "hello,"+name; }else{ return "hello,provider-"+name; } }
服務消費者
@RequestMapping("/test") String test(String name,Integer type);
會遇到報錯Method has too many Body parameters
說明:
如果服務消費者傳過來引數時,全都用的是@RequestParam的話,那麼服務提供者的Controller中對應引數前可以寫@RequestParam,也可以不寫
服務消費者feign呼叫時,在所有引數前加上@RequestParam註解
正確的寫法
@RequestMapping("/test") String test(@RequestParam("name") String name,@RequestParam("type") Integer type);
(2)POST
如果接收方不變
服務消費者
@RequestMapping("/test") String test(@RequestBody String name,@RequestBody Integer type);
會遇到報錯Method has too many Body parameters
服務消費者為
@RequestMapping("/test") String test(@RequestBody String name,@RequestParam("type") Integer type);
name的值會為null
說明:
如果服務消費者傳過來引數,有@RequestBody的話,那麼服務提供者的Controller中對應引數前必須要寫@RequestBody
正確的寫法
服務提供者
@RequestMapping("/test") public String test(@RequestBody String name,Integer type){ if(type==1){ return "hello,"+name; }else{ return "hello,provider-"+name; } }
服務消費者正確的寫法
@RequestMapping("/test") String test(@RequestBody String name,@RequestParam("type") Integer type);
可以接收到引數
總結:
- 請求引數前加上註解@PathVariable、@RequestParam或@RequestBody修飾
- 可以有多個@RequestParam,但只能有不超過一個@RequestBody
- 使用@RequestParam註解時必須要在後面加上引數名
- @RequestBody用來修飾物件,但是既有@RequestBody也有@RequestParam,那麼引數就要放在請求的url中,@RequestBody修飾的就要放在提交物件中
- 當引數比較複雜時,feign即使宣告為get請求也會強行使用post請求
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。