FeignClient的參數傳遞給服務提供方的方式(簡單數據類型、對象)


1、簡單數據類型的參數采用的restFull的方式,發送Get請求

服務提供方的controller:

//類名加了窄化請求:@RequestMapping(path =  "house",produces = "application/json;charset=utf-8")
@GetMapping("/getHousesByUser/{userid}") public JSONResult<House> getHousesByUser(@PathVariable("userid")Integer userId) throws Exception{

服務使用方的FeignCilent接口:

@GetMapping("/house/getHousesByUser/{userid}")
public JSONResult<?> getHousesByUser(@PathVariable("userid")Integer userId) throws Exception;

服務使用方controller:

@GetMapping("/queryHouse/{userId}")
public JSONResult<?> queryHouse(@PathVariable("userId") Integer userId) throws Exception {
    return houseServiceClient.getHousesByUser(userId);
}

2、簡單數據類型不使用restFull風格的方式發送Get請求

 服務提供方的controller:

//@RequestParam("name") 將傳入的參數名改為指定名
@GetMapping("/test1")
public JSONResult test1(Integer id, @RequestParam("name")String uname) throws Exception{

服務使用方的FeignCilent接口:

@GetMapping("/house/test1")
public JSONResult test1(@RequestParam("id")Integer id, @RequestParam("name")String name) throws Exception;

服務使用方controller:

@GetMapping("/testHouse1")
public JSONResult<?> testHouse1(Integer id, String name) throws Exception {
    return houseServiceClient.test1(id, name);
}

FeignClient接口的方法上必須使用@RequestParam 注解,

如果FeignClient傳遞的參數名與服務提供方的Controller方法的參數名不一樣, 需要在服務提供方, 使用@RequestParam進行映射

3、javaBean對象,發送Post請求

  SpringCloud默認使用json的形式發送給服務提供方, 默認只能使用post的提交方式

服務提供方的controller: 注意服務提供方必須也加上@RequestBody注解保證格式一致

@PostMapping("/test3")
public JSONResult test3(Integer id, @RequestBody  Condition condition) throws Exception{
    JSONResult jsonResult  = new JSONResult<>();
    return jsonResult;
} 

服務使用方的FeignCilent接口:

@PostMapping("/house/test3")
public JSONResult test3(@RequestParam("id")Integer id, @RequestBody  Condition condition) throws Exception;

服務使用方controller:

@GetMapping("/testHouse3") //服務提供方隨便使用get/post請求 public JSONResult<?> testHouse3(Integer id, Condition condition) throws Exception {
    return houseServiceClient.test3(id, condition);
}

要求: FeignClient接口的方法的javaBean參數, 添加@RequestBody,  要求服務的提供方的方法上也要加@RequestBody注解

注意: 一個方法上只能有一個@RequestBody注解, 但是可以有多個@RequestParam注解

4、使用@SpringQueryMap,發送的javaBean對象的數據類型(不推薦)

  默認只能使用post的提交方式  如果想讓get能夠發送javaBean數據,

在SpringBoot2.1.* 版本之上, 提供了一個@SpringQueryMap

服務提供方的controller:

@GetMapping("/test2")
public JSONResult test2( Condition condition) throws Exception{
    JSONResult jsonResult  = new JSONResult<>();
    jsonResult.setData(condition);
    return jsonResult;
} 

服務使用方的FeignCilent接口:

@GetMapping("/house/test2")
public JSONResult test2( @SpringQueryMap Condition condition) throws Exception;

服務使用方controller:

@GetMapping("/testHouse2")
public JSONResult<?> testHouse2(Integer id, Condition condition) throws Exception {
    return houseServiceClient.test2( condition);
}

 


免責聲明!

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



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