@FeignClient服务之间调用

需要使用 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类中的映射方法一致

posted on   何苦->  阅读(5722)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示