springboot项目下,控制层发起任务,在service层开启一个thread线程执行相关操作,当控制层返回之后,子线程就获取不到主线程的request的相关信息,这应该怎么解决?
@Undest
controller:
public class ControllerReportController {
private static InheritableThreadLocal<HttpServletRequest> threadLocalData = new InheritableThreadLocal<>();
@Autowired
ControllerReportService controllerReportService;
@RequestMapping("/test")
public void test(HttpServletRequest request) {
String userId = request.getHeader("userId");
log.info(userId);
threadLocalData.set(request);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
controllerReportService.test(threadLocalData);
}
});
thread.start();
log.info("主线程结束");
}
}
service:
public class ControllerReportServiceImpl implements ControllerReportService {
@Override
public void test(InheritableThreadLocal<HttpServletRequest> threadLocalData) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
HttpServletRequest httpServletRequest = threadLocalData.get();
String userId = httpServletRequest.getHeader("userId");
log.info(String.valueOf(userId));
}
}
结果
[INFO ] [164] [2023-08-02 11:45:31] 293
[INFO ] [164] [2023-08-02 11:45:31] 主线程结束
[INFO ] [164] [2023-08-02 11:45:31] RequestId:1690947931271, 本次请求耗时SpeedTime:4ms
[INFO ] [745] [2023-08-02 11:45:36] null
更新:
下面的代码经过我个人测试可以跑通:
Controller:
Service:
请求:
结果:
可以看到在主线程返回后子线程依然能够拿到request里的值