@Configuration public class AsyncConfig extends AsyncConfigurerSupport { public class ContextAwareCallable<T> implements Callable<T> { private Callable<T> task; private RequestAttributes context; public ContextAwareCallable(Callable<T> task, RequestAttributes context) { this.task = task; this.context = context; } @Override public T call() throws Exception { if (context != null) { RequestContextHolder.setRequestAttributes(context); } try { return task.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } } public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor { @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes())); } @Override public <T> ListenableFuture<T> submitListenable(Callable<T> task) { return super.submitListenable(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes())); } } @Override @Bean public Executor getAsyncExecutor() { return new ContextAwarePoolExecutor(); } }
————————————————
版权声明:本文为CSDN博主「硕说烁」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhangshuo1996123/article/details/124861692