feign远程调用丢失请求头(header)解决方案以及原理分析!

本文分析了Feign在远程调用时请求头丢失的原因,并提供了解决方案,即通过实现Feign拦截器手动添加请求头。同时,针对Feign异步调用中请求头丢失的问题,提出了使用ThreadLocal共享数据来保持请求头信息的方法。
摘要由CSDN通过智能技术生成

一、Feign远程调用丢失请求头问题

Feign在远程调用时,会重新包装请求(请求路径,请求参数)但是不会携带请求头,所以在到达被调服务时没有请求头信息

 原因:

  @Override
  public Object invoke(Object[] argv) throws Throwable {
    RequestTemplate template = buildTemplateFromArgs.create(argv);
    Options options = findOptions(argv);
    Retryer retryer = this.retryer.clone();
    while (true) {
      try {
        return executeAndDecode(template, options);
      } catch (RetryableException e) {
        try {
          retryer.continueOrPropagate(e);
        } catch (RetryableException th) {
          Throwable cause = th.getCause();
          if (propagationPolicy == UNWRAP && cause != null) {
            throw cause;
          } else {
            throw th;
          }
        }
        if (logLevel != Logger.Level.NONE) {
          logger.logRetry(metadata.configKey(), logLevel);
        }
        continue;
      }
    }
  }

feign会重新封装请求模板。这个模板中没有请求头信息。

解决方案,利用feign拦截器,手动添加请求头:

 参考代码:

@Configuration
public class GuliFeignConfig {

    /**
     * 解决fein远程调用丢失请求头
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 1、RequestContextHolder 拿到当前的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    // 原始请求 页面发起的老请求
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        // 获取原始请求的头数据 cookie
                        String cookie = request.getHeader("Cookie");

                        // 给feign生成的心请求设置请求头cookie
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}

2、Feign异步调用丢失请求头问题

解决:获取之前的请求,让每个异步任务的线程共享ThreadLocal数据

  /**
   * 解决异步任务拿不到ThreadLocal里的数据
   * 获取之前的请求,让每个异步任务的线程共享ThreadLocal数据
   */
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
			// 解决异步任务拿不到ThreadLocal里的数据
            RequestContextHolder.setRequestAttributes(requestAttributes); 

            //...
        }, executor);

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangkaixuan456

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值