问题出现场景:因业务需要高效批量处理,于是起了线程池,异步批量处理,但是处理操作的代码中获取用户信息失败 !!!
debug时发现异步子线程中的SecurityContextHolder为null,鉴权信息不存在,原因是:
研究SecurityContextHolder, SecurityContext和Authentication对象的内容,发现安全上下文默认是存储在ThreadLocal也就是线程本地的,启动其他线程执行的时候,当然就会丢失掉上下文信息;
于是,想到解决办法:在起异步子线程时,手动的把主线程上下文的值也给子线程塞一份,最后在执行完操作后再手动清除子线程中的安全上下文;
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(pooCount);
try {
SecurityContext securityContext = SecurityContextHolder.getContext();
for (int i = 0; i < pooCount; i++) {
fixedThreadPool.execute(new Runnable() {
public void run() {
Response response = new Response();
try {
// 手动把主线程的安全信息给子线程一份
SecurityContextHolder.setContext(securityContext);// 2
userContextHolder.prepareUserContext(request);
// 具体的处理操作
} catch (Exception e) {
} finally {
// 清除操作
SecurityContextHolder.clearContext();// 3
}
}
});
}
} catch (IOException e) {
} finally {
latch.await();
fixedThreadPool.shutdown();
}