Get请求中,包含多个参数
在Get接口中,使用包含多个属性的对象来来接收多个参数
@GetMapping("/test")
public void test(User user) {
//省略……
}
@Data
public class User implements Serializable {
private Integer id;
private String username;
}
此时,请求的URL需要为
/test?id=1&username=qqcr
使用FeignClient来请求上述Get接口
- 方法一
在feign client中,使用User对象作为参数,但是需要在参数前面加上@SpringQueryMap注解,来让框架将User对象解析成方法二的样子
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
@GetMapping("/test")
public User get0(@SpringQueryMap User user);
}
- 方法二
@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);
}
- 方法三
这种方式不推荐,因为不知道map中需要什么属性,可读性不高。
而且如果参数为空的时候会有一些问题,例如 map.put(“username”, null); 会导致microservice-provider-user 服务接收到的username是"" ,而不是null。
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get2(@RequestParam Map<String, Object> map);
}
但是在调用的时候,需要使用如下代码的方式来构建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);
}
- 错误的调用示范
如果直接使用类似于方法一种的方法,不加@SpringQueryParam,则方法会被自动转换为POST请求,然后报错。
调用代码如下
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/test", 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"}
Post请求包含多个参数
定义接口,使用对象接收参数
User对象前需要加上@RequestBody注解。
@RestController
public class UserController {
@PostMapping("/test2")
public User post(@RequestBody User user) {
...
}
}
使用Feign进行调用,传入对象作为参数
User对象前需要加上@RequestBody注解。
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/test2", method = RequestMethod.POST)
public User post(@RequestBody User user);
}