原理也简单,做个静态代理就行了
public static void execute(Runnable runnable) {
ThreadPoolExecutorHolder.THREAD_POOL_EXECUTOR.execute(RunnableProxy.wrapper(runnable));
}
private static class RunnableProxy implements Runnable {
private RequestAttributes requestAttributes;
private SecurityContext context;
private Runnable runnable;
private RunnableProxy(Runnable runnable) {
// 把登录信息传递给异步线程
this.context = SecurityContextHolder.getContext();
this.requestAttributes = RequestContextHolder.getRequestAttributes();
this.runnable = runnable;
}
public static RunnableProxy wrapper(Runnable runnable) {
return new RunnableProxy(runnable);
}
@Override
public void run() {
try {
// 共享request,让ZYRequestUtils.getRequest生效
SecurityContextHolder.setContext(this.context);
ZYRequestUtils.shareRequest(requestAttributes);
runnable.run();
} finally {
// 清掉当前子线程的request,避免线程池串味
ZYRequestUtils.removeRequest();
SecurityContextHolder.clearContext();
}
}
}