java定时任务中java.lang.IllegalStateException: No thread-bound request found
在定义线程池之前加入两行代码,设置request子线程共享。线程池中的子线程获取不到定时任务主线程的。xxljob定时任务中写了一个。
问题描述:
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);
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)