callable包装
public class ContextAwareCallableimplements Callable { private Callable task; private RequestAttributes context; public ContextAwareCallable(Callable 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(); } }}
threadpool包装
public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor { @Override publicFuture submit(Callable task) { return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes())); } @Override public ListenableFuture submitListenable(Callable task) { return super.submitListenable(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes())); }}
异步线程配置
@Configurationpublic class ExecutorConfig extends AsyncConfigurerSupport { @Override @Bean public Executor getAsyncExecutor() { return new ContextAwarePoolExecutor(); }}
doc
想获取最新内容,请关注微信公众号