问题描述:
xxljob定时任务中写了一个线程池,每次调用定时任务,都会起7条线程,进行数据传输,程序运行时报错:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
bug原因:
线程池中的子线程获取不到定时任务主线程的request信息
解决方法:
在定义线程池之前加入两行代码,设置request子线程共享
// 子线程request共享
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(sra, true);
// 定义线程池名称
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("my-pool-%d").build();
//创建线程池
ThreadPoolExecutor blockchainSavePool = new ThreadPoolExecutor(
7,
7,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10),
namedThreadFactory);