Spring Cloud Feign 请求时附带请求头怎么解决
更新:HHH   时间:2023-1-7


今天就跟大家聊聊有关Spring Cloud Feign 请求时附带请求头怎么解决,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

解决方案 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

看完上述内容,你们对Spring Cloud Feign 请求时附带请求头怎么解决有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注天达云行业资讯频道,感谢大家的支持。

返回开发技术教程...