现象
接收request请求,第一次获取到了param,第二次获取不到
原因
第一次接受到request之后,把request存储在
TransmittableThreadLocal<HttpServletRequest> REQUEST_THREAD_LOCAL = new TransmittableThreadLocal<>()
当中以便给异步线程使用,由于controller线程exe1已经执行完成了,但是controller创建的子线程还没有执行完但是占用着request,导致request中有个属性状态值没有改变,后面新的请求又使用了同个线程exe1,导致request不会赋值新的param
解决方案
controller起子线程使用如下方式,使用完关闭线程池
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
RequestUtil.shareRequest(request);
ExecutorService executorService = ThreadUtil.newExecutor(10 ,10);
// 如果没有使用Ttl线程来处理,会有线程安全问题,并发量大会出现获取不到数据的情况
ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);
try {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String token = userInfoManager.getToken();
if (token == null) {
logger.info("test1 token is null");
}
return "yes";
}, ttlExecutorService);
CompletableFuture.allOf(new CompletableFuture[]{completableFuture}).join();
String result = null;
try {
result = completableFuture.get();
logger.info("result:{}", result);
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
RequestUtil.removeShareRequest();
ttlExecutorService.shutdown();
}