关于微服务RPC远程调用,之前已经简单介绍过feign以及openfeign,并且就参数传递与接收也进行过简单讲解。
    Nacos+Feign简单使用:https://blog.csdn.net/u011177064/article/details/104309921
    本文继续介绍feign采用实体对象作为请求响应参数具体怎么使用。

    以下是几种常见的用法:
    1、
    请求参数: GET请求,请求参数按字段名使用@RequestParam注解,并且里面的 value 必须和 服务生产者的参数名一致
    响应参数: 实体+泛型
    消费者-请求

    1. //表示该接口的方法由feign实现远程调用,
    2. //目标接口地址示例: jfcloud-mall-storage/storage/getStorages
    3. @FeignClient(name = "jfcloud-mall-storage") //jfcloud-mall-storage在nacos中已注册
    4. public interface StorageServiceClient {
    5. @GetMapping(path = "/storage/getStorages")
    6. public RespDataT<List<JfcloudStorage>> getStoragesByEntity(@RequestParam("productIds") Long[] productIds);
    7. }

    生产者-响应 (springboot控制器)

    1. @ApiOperation("商品库存查询")
    2. @GetMapping(path = "/getStorages")
    3. @ResponseBody
    4. public RespDataT<List<JfcloudStorage>> getStorages(StorageQueryForm query)
    5. //query对象
    6. @Data
    7. public class StorageQueryForm {
    8. @ApiModelProperty(value = "商品ID (多个)")
    9. private Long[] productIds;
    10. }

    2、
    请求参数: POST请求,JSON数据,使用@RequestBody注解
    消费者-请求

    1. @FeignClient(name = ServiceNames.mall_storage)
    2. public interface StorageServiceClient {
    3. @PostMapping(path = "/storage/deductStorage",consumes = "application/json", produces = "application/json")
    4. RespData deductStorage(@RequestBody StorageDeductForm form);
    5. }

    生产者-响应 (springboot控制器)

    1. @ApiOperation("扣减库存")
    2. @PostMapping(path = "/deductStorage",consumes = "application/json", produces = "application/json")
    3. @ResponseBody
    4. public RespDataT<JfcloudStorage> deductStorage(@RequestBody StorageDeductForm form)

    使用实体接收数据时要注意泛型的正确使用。

    1. public class RespDataT<T>{
    2. public static final int Success = 1;
    3. public static final int Error = 0;
    4. private int status;
    5. private T datas ;
    6. public RespDataT(T datas) {
    7. this.datas = (T)datas;
    8. this.status =Success;
    9. }
    10. public RespDataT() {
    11. }
    12. public int getStatus() {
    13. return status;
    14. }
    15. public void setStatus(int status) {
    16. this.status = status;
    17. }
    18. public T getDatas() {
    19. return datas;
    20. }
    21. public void setDatas(T datas) {
    22. this.datas = datas;
    23. }
    24. }

    最开始的时候,因为 public void setDatas(T datas) 写成了 public void setDatas(Object datas) ,
    所以feign把返回数据自动转成了Map,所以要注意一下