原文:http://www.itmuch.com/spring-cloud-sum/feign-multiple-params/web
本節來探討如何使用Feign構造多參數的請求。筆者以GET及POST請求爲例講解,其餘方式(例如DELETE、PUT等)的請求原理相通,讀者可自行研究。spring
假設需請求的URL包含多個參數,例如http://microservice-provider-user/get?id=1&username=張三
,該如何使用Feign構造呢?app
咱們知道,Spring Cloud爲Feign添加了Spring MVC的註解支持,那麼咱們不妨按照Spring MVC的寫法嘗試一下:ide
@FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get0(User user); }
然而,這種寫法並不正確,控制檯會輸出相似以下的異常。post
feign.FeignException: status 405 reading UserFeignClient#get0(User); content:
{"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}
由異常可知,儘管咱們指定了GET方法,Feign依然會使用POST方法發送請求。this
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get1(@RequestParam("id") Long id, @RequestParam("username") String username); }
這是最爲直觀的方式,URL有幾個參數,Feign接口中的方法就有幾個參數。使用@RequestParam註解指定請求的參數是什麼。spa
多參數的URL也可以使用Map來構建。當目標URL參數很是多的時候,可以使用這種方式簡化Feign接口的編寫。code
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get2(@RequestParam Map<String, Object> map); }
在調用時,可以使用相似如下的代碼。blog
public User get(String username, String password) { HashMap<String, Object> map = Maps.newHashMap(); map.put("id", "1"); map.put("username", "張三"); return this.userFeignClient.get2(map); }
下面來討論如何使用Feign構造包含多個參數的POST請求。假設服務提供者的Controller是這樣編寫的:接口
@RestController public class UserController { @PostMapping("/post") public User post(@RequestBody User user) { ... } }
咱們要如何使用Feign去請求呢?答案很是簡單,示例:
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/post", method = RequestMethod.POST) public User post(@RequestBody User user); }