Spring Cloud Alibaba 之 “Feign多参数构造”

时间:2024-12-05 06:57:17

在上一篇文章整合好了Feign,现在来总结以下Feign调用多参数方法的使用。

GET方式:

Spring Cloud为Feign支持了Spring Mvc注解的。如果请求的是localhost:8083/test?id=1&name=coco,那么如果我们这样写(User实体类有这二个属性)

@FeignClient("people-center")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User test(User user);
}

这样其实是会报错的,因为即使我们指定了GET,但是Feign还是会以POST方式请求,所以我们需要修改成如下这样的

@FeignClient("people-center")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User test(@SpringQueryMap User user);
}

或者是

@FeignClient("people-center")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User test(@RequestParam("id") Long id,@RequestParam("name") String name);
或者是
 @FeignClient("people-center")
  public interface UserFeignClient {
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public User test(@RequestParam Map<String, Object> map);
  }
  

推荐使用第二种,因为比较直观

POST请求

代码解读

    @FeignClient("people-center")
    public interface UserFeignClient {
      @RequestMapping(value = "/post", method = RequestMethod.POST)
      public User test(@RequestBody User user);
    }

POST请求就很简单了,直接按照上面方式写就行了