我是靠谱客的博主 耍酷篮球,这篇文章主要介绍 如何在async线程中访问RequestContextHolder,现在分享给大家,希望可以做个参考。

callable包装

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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(); } } }

threadpool包装

复制代码
1
2
3
4
5
6
7
8
9
10
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())); } }

异步线程配置

复制代码
1
2
3
4
5
6
7
8
@Configuration public class ExecutorConfig extends AsyncConfigurerSupport { @Override @Bean public Executor getAsyncExecutor() { return new ContextAwarePoolExecutor(); } }

doc

  • How to enable request scope in async task executor


想获取最新内容,请关注微信公众号

图片描述

最后

以上就是耍酷篮球最近收集整理的关于 如何在async线程中访问RequestContextHolder的全部内容,更多相关内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部