直接上代码
// 在线程外部获取到requestAttributes
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// 线程池调用
executorService.submit(() -> {
// 然后在在线程内部将requestAttributes 设置到RequestContextHolder中去
RequestContextHolder.setRequestAttributes(requestAttributes);
//将主线程的token更新到子线程全局变量中
assert requestAttributes != null;
ThreadLocalUtil.set("token", requestAttributes.getRequest().getHeader("token"));
// 方法主体
return xxxx();
});
FeignConfig
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
String token= request.getHeader("token");
if (StringUtils.isBlank(token)){
// 重点
token= ThreadLocalUtil.get("token");
}
log.info("token={}", token);
//添加token
requestTemplate.header("token", token);
}
}
网友评论