ThreadLocal
同一个线程内共享数据
public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>(); // 赋值 toThreadLocal.set(userInfoTo);
// 取值
UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
Feign远程调用丢失请求头问题
解决
加上 feign 远程调用的请求拦截器,在每次发送远程请求之前,把老请求的数据同步过来,这样就可以解决请求头的丢失问题了。
package com.xunqi.gulimall.order.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;
/**
* @Description: feign拦截器功能
* @Created: with IntelliJ IDEA.
* @author: 夏沫止水
* @createTime: 2020-07-02 21:10
**/
@Configuration
public class GuliFeignConfig {
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor() {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
//1、使用RequestContextHolder拿到刚进来的请求数据
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
//老请求
HttpServletRequest request = requestAttributes.getRequest();
if (request != null) {
//2、同步请求头的数据(主要是cookie)
//把老请求的cookie值放到新请求上来,进行一个同步
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
}
}
};
return requestInterceptor;
}
}
异步任务丢失上下文问题
获取异步任务所使用的线程,与主任务的线程不同,所以异步任务无法获取主任务的上下文环境。
解决
将主线程中原始请求的上下文数据共享出来,在新开启的异步任务中重新设置上下文数据,即可解决
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//每一个线程都来共享之前的请求数据
RequestContextHolder.setRequestAttributes(requestAttributes);