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

 

posted @ 2020-07-13 19:07  64Byte  阅读(1380)  评论(0编辑  收藏  举报