SpringBoot Test 多线程报错的根本原因(dataSource already closed)
背景
使用Springboot test进行相关测试的时候,发现开启线程操作数据库的时候异常。
排查方法
将线程移除,采用并行的方式,操作数据库正常。
根本原因
- SpringBoot Test 主线程退出,导致Spring 容器关闭。
- Spring容器关闭,导致DruidDataSource 关闭
- 此时用户线程去访问已关闭的数据源,导致报错。
解决方法
提供一个全局的线程池,然后使用线程池开启线程操作,然后添加监听器,监听线程池里面是否有未完成的任务,如果有则不关闭容器。
@Component public class EventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextClosedEvent) { LoggerClient.info("容器即将关闭"); //线程池工具类 ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil(); while (threadPoolUtil.getExecutor().isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
public class ThreadPoolUtil { private static final ExecutorService executor = Executors.newFixedThreadPool(20); public ThreadPoolUtil() { } public ExecutorService getExecutor() { return executor; } public static void submitRunnable(Runnable runnable) { executor.submit(runnable); } public static <V> Future submitCallable(Callable<V> callable) { Future<V> submit = executor.submit(callable); return submit; } }
到此这篇关于SpringBoot Test 多线程报错:dataSource already closed的文章就介绍到这了,更多相关SpringBoot Test 多线程报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
springboot2.2 集成 activity6实现请假流程(示例详解)
这篇文章主要介绍了springboot2.2 集成 activity6实现请假完整流程示例详解,本文通过示例代码图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-07-07jackson 实体转json 为NULL或者为空不参加序列化(实例讲解)
下面小编就为大家带来一篇jackson 实体转json 为NULL或者为空不参加序列化(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-10-10IntelliJ IDEA 刷题利器 LeetCode 插件详解
这篇文章主要介绍了IntelliJ IDEA 刷题利器 LeetCode 插件,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-08-08
最新评论