关于微服务RPC远程调用,之前已经简单介绍过feign以及openfeign,并且就参数传递与接收也进行过简单讲解。
Nacos+Feign简单使用:https://blog.csdn.net/u011177064/article/details/104309921
本文继续介绍feign采用实体对象作为请求响应参数具体怎么使用。
以下是几种常见的用法:
1、
请求参数: GET请求,请求参数按字段名使用@RequestParam注解,并且里面的 value 必须和 服务生产者的参数名一致
响应参数: 实体+泛型
消费者-请求
//表示该接口的方法由feign实现远程调用,
//目标接口地址示例: jfcloud-mall-storage/storage/getStorages
@FeignClient(name = "jfcloud-mall-storage") //jfcloud-mall-storage在nacos中已注册
public interface StorageServiceClient {
@GetMapping(path = "/storage/getStorages")
public RespDataT<List<JfcloudStorage>> getStoragesByEntity(@RequestParam("productIds") Long[] productIds);
}
生产者-响应 (springboot控制器)
@ApiOperation("商品库存查询")
@GetMapping(path = "/getStorages")
@ResponseBody
public RespDataT<List<JfcloudStorage>> getStorages(StorageQueryForm query)
//query对象
@Data
public class StorageQueryForm {
@ApiModelProperty(value = "商品ID (多个)")
private Long[] productIds;
}
2、
请求参数: POST请求,JSON数据,使用@RequestBody注解
消费者-请求
@FeignClient(name = ServiceNames.mall_storage)
public interface StorageServiceClient {
@PostMapping(path = "/storage/deductStorage",consumes = "application/json", produces = "application/json")
RespData deductStorage(@RequestBody StorageDeductForm form);
}
生产者-响应 (springboot控制器)
@ApiOperation("扣减库存")
@PostMapping(path = "/deductStorage",consumes = "application/json", produces = "application/json")
@ResponseBody
public RespDataT<JfcloudStorage> deductStorage(@RequestBody StorageDeductForm form)
使用实体接收数据时要注意泛型的正确使用。
public class RespDataT<T>{
public static final int Success = 1;
public static final int Error = 0;
private int status;
private T datas ;
public RespDataT(T datas) {
this.datas = (T)datas;
this.status =Success;
}
public RespDataT() {
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public T getDatas() {
return datas;
}
public void setDatas(T datas) {
this.datas = datas;
}
}
最开始的时候,因为 public void setDatas(T datas) 写成了 public void setDatas(Object datas) ,
所以feign把返回数据自动转成了Map,所以要注意一下