温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Cloud Feign 请求时附带请求头怎么解决

发布时间:2020-10-27 19:42:35 来源:亿速云 阅读:831 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关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 请求时附带请求头怎么解决有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI