解决Spring Cloud Feign 请求时附带请求头的问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

解决Spring Cloud Feign 请求时附带请求头的问题

乐之终曲   2020-10-19 我要评论

问题描述

Feign 在请求时是不会将 request 的请求头带着请求的,导致假如 Feign 调用的接口需要请求头的信息,比如当前用户的 token 之类的就获取不到

解决方案 FeignConfiguration

通过实现 Feign 的 RequestInterceptor 将从上下文中获取到的请求头信息循环设置到 Feign 请求头中。

/**
 * feign 配置文件
 * 将请求头中的参数,全部作为 feign 请求头参数传递
 * @author: linjinp
 * @create: 2020-06-28 09:54
 **/
@Configuration
public class FeignConfiguration implements RequestInterceptor {
  @Override
  public void apply(RequestTemplate requestTemplate) {
    HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String values = request.getHeader(name);
        requestTemplate.header(name, values);
      }
    }
  }
}

使用

通过 configuration = FeignConfiguration.class 指定这次 Feign 请求走哪种配置

@FeignClient(name = "admin", contextId = "factoryPlmseriesRelation", configuration = FeignConfiguration.class)
//@FeignClient(name = "admin2", contextId = "factoryPlmseriesRelation", url = "http://127.0.0.1:8582/", configuration = FeignConfiguration.class)
public interface FeignFactoryPlmseriesRelationService {

  /**
   * 根据当前用户,获取工厂与PLM关联关系
   * @return
   */
  @GetMapping(value = "/factoryPlmseriesRelation/getFactoryPlmseriesRelation")
  ErrorMsg<List<FactoryPlmseriesRelationVo>> getFactoryPlmseriesRelation();

}

配置修改

主要是 hystrix.command.default.execution.isolation 后面的配置,需要将 hystrix 配置为信号量模式,否则会出现由于隔离策略导致获取不到请求头

# ribbon 配置
ribbon:
 OkToRetryOnAllOperations: false #对所有操作请求都进行重试,默认false
 ReadTimeout: 5000  #负载均衡超时时间,默认值5000
 ConnectTimeout: 5000 #ribbon请求连接的超时时间,默认值2000
 MaxAutoRetries: 0   #对当前实例的重试次数,默认0
 MaxAutoRetriesNextServer: 1 #对切换实例的重试次数,默认1
# hystrix 配置
hystrix:
 command:
  default: #default全局有效,service id指定应用有效
   execution:
    timeout:
     #是否开启超时熔断
     enabled: true
    isolation:
     thread:
      timeoutInMilliseconds: 10000 #断路器超时时间,默认1000ms
     # hystrix 隔离模式改为信号量模式,feign 才能获取到父线程中的请求头
     strategy: SEMAPHORE
     # 允许的并发量,默认值为 10
     semaphore:
      maxConcurrentRequests: 100

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们