如何使用Feign構造多參數的請求


原文:http://www.itmuch.com/spring-cloud-sum/feign-multiple-params/

 

本節來探討如何使用Feign構造多參數的請求。筆者以GET及POST請求為例講解,其他方式(例如DELETE、PUT等)的請求原理相通,讀者可自行研究。

GET請求多參數的URL

假設需請求的URL包含多個參數,例如http://microservice-provider-user/get?id=1&username=張三 ,該如何使用Feign構造呢?

我們知道,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方法發送請求。

正確寫法如下

方法一

@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注解指定請求的參數是什么。

方法二

多參數的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請求包含多個參數

下面來討論如何使用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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM