美文网首页
@FeignClient服务之间调用Get请求传递对象参数、经验

@FeignClient服务之间调用Get请求传递对象参数、经验

作者: 拄杖忙学轻声码 | 来源:发表于2021-09-14 17:40 被阅读0次

一、需要使用 feign 自己的 httpclient 发送协议,引入如下依赖,即可实现get请求方式传递对象

        <!-- openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
 
        <!-- 使用 openfeign 自家的 feign httpclient 代替 Apache httpclient 发送请求 -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>10.1.0</version>
        </dependency>

二、调用方 @FeignClient 端代码示例:

@FeignClient(value = "gateway-service",configuration = FeignConfigure.class)
// 第一个"/xxx"是 gateway-service 网关应用访问的根目录(即路由转发之前的断言匹配规则)
@RequestMapping(value = {"/xxx/xxx"})
public interface AssessFeignClient {
 
    @GetMapping("/getBusinessListByCondition")
    CommonResult<List<Business>> getBusinessListByCondition(Business business);
 
    @GetMapping("/getVhclEvaByCustIntentId")
    CommonResult<List<VhclEva>> getVhclEvaByCustIntentId(@RequestParam("custIntentId") Integer custIntentId);
 
}

三、被调用方的 Controller 层接口示例:

    @GetMapping("/getBusinessListByCondition")
    public CommonResult<List<Business>> getBusinessListByCondition(HttpServletRequest request,@RequestBody Business business){
        Integer loginUserId = RequestUtil.userId(request);
        Integer dlrId = RequestUtil.dlrId(request);
 
        LambdaQueryWrapper<Business> businessQwParam = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotNull(business) && NumCode.ONE.equals(business.getReqSource()) && StrUtil.isNotBlank(business.getVin())){
            businessQwParam
                    .eq(Business::getVin, business.getVin())
                    .apply(" CREATE_DATE = (select max(CREATE_DATE) from tt_business where VIN = {0} ) ", business.getVin())
                    .eq(Business::getDlrId, dlrId);
            return success(businessService.list(businessQwParam));
        }
 
        return success(null);
    }

说明:
1、无论是 get 还是 post 请求方式,只要传递的参数是对象类型,FeignClient 端的接口方法对象类型参数不需要加 @RequestBody 注解,而 controller 层的接收接口方法必须加上 @RequestBody 注解,否则参数无法传递进来。猜测可能是只要传递对象参数,feign httpclient 就默认把 get 请求方式转换为 post 请求方式

2、如果传递的是简单类型的参数,则 FeignClient 端的接口方法参数 和 Controller层的接收接口方法参数(包括注解)一致就可以了

3、如果是 post 请求方式,可能会报请求超时的错误,因为 OpenFeign 的默认请求连接时间仅有几秒钟,需要把请求时间配置的更长一些,如下配置:
方式一:

# 配置 feign 默认请求时间仅几秒钟,配置请求时间长一些(毫秒)
feign:
  client:
    config:
      default:
        connectTimeout: 10000
        readTimeout: 600000

方式二:

# 配置 feign 默认请求时间仅几秒钟,配置请求时间长一些(毫秒)
ribbon:
  ReadTimeout: 60000
  ConnectTimeout: 60000

总结:
1、服务之间采用多维护方式调用,多维护封装类数据传输对象、代理(@FeignClient标注)接口类
2、代理接口类中的方法一般最好与被调用服务中Controller类中的映射方法一致

相关文章

网友评论

      本文标题:@FeignClient服务之间调用Get请求传递对象参数、经验

      本文链接:https://www.haomeiwen.com/subject/sggcgltx.html