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"}
Spring Cloud如何使用Feign構造多引數的請求,以GET以及POST方法的請求為例進行講解
這個方法有兩個引數,而Feign去對映的時候它不會去自動給你區分那個引數是哪個,會直接給你報錯
解決方法: 添加註解,自己去指定要對映的屬性
GET請求多引數的URL
假設我們請求的URL包含多個引數,例如http://microservice-provider-user/get?id=1&username=張三 ,要如何構造呢?
我們知道,Spring Cloud為Feign添加了Spring MVC的註解支援,那麼我們不妨按照Spring MVC的寫法嘗試一下:
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get0(User user);
}
然而,這種寫法並不正確,控制檯會輸出類似如下的異常。
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方法傳送請求。
正確寫法如下:
(1) 方法一
@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註解指定請求的引數是什麼。
(2) 方法二
多引數的URL也可使用Map來構建。當目標URL引數非常多的時候,可使用這種方式簡化Feign介面的編寫。
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get2(@RequestParam Map<String, Object> map);
}
在呼叫時,可使用類似以下的程式碼。
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);
}
POST請求包含多個引數
@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);
}