原文: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); }