1. 程式人生 > 實用技巧 >FeignClient的引數傳遞給服務提供方的方式(簡單資料型別、物件)

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:

@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);
}