原因

调用了拦截器

解决配置(非异步)

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
32
33
34
35
36
37
38
package com.jhj.gulimall.product.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeginConfig {


@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor(){

return new RequestInterceptor() {

@Override
public void apply(RequestTemplate requestTemplate) {


//拿到刚进来的原请求信息 底层利用threadlocal 所以异步时会再次重现问题
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=requestAttributes.getRequest();
//同步请求头数据 例如Cookie requestTemplate是新的要发送的请求
if(request != null){

String cookie = request.getHeader("Cookie");
requestTemplate.header("Cookie",cookie);
}

}
};
}
}

解决异步

需要结合 非异步配置

1
2
3
4
5
6
7
8
9
10
//在异步方法执行前获取request
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
CompletableFuture.runAsync(()->{

//在异步方法执行时在写入request
RequestContextHolder.setRequestAttributes(requestAttributes)
System.out.println("当前线程"+Thread.currentThread().getId());
int i=10/2;
System.out.println("运行结果"+i);
},executor);

作者声明

1
如有问题,欢迎指正!