在使用Springboottest进行相关测试的时候,发现开启线程操作数据库的时候异常,这篇文章主要介绍了SpringBootTest多线程报错:dataSourcealreadyclosed的根本原因及解决方法,需要的朋友可以参考下
背景
使用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 多线程报错内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:SpringBoot Test 多线程报错的根本原因(dataSource already closed)
基础教程推荐
猜你喜欢
- 是否适合从javabean类更新数据库? 2023-11-04
- springboot下使用shiro自定义filter的个人经验分享 2024-02-27
- JSP 动态树的实现 2023-12-17
- 使用Java和WebSocket实现网页聊天室实例代码 2024-02-25
- Java编写实现窗体程序显示日历 2023-01-02
- 深入理解约瑟夫环的数学优化方法 2024-03-07
- Java+mysql实现学籍管理系统 2023-03-16
- Java中EnvironmentAware 接口的作用 2023-01-23
- 运用El表达式截取字符串/获取list的长度实例 2023-08-01
- JavaWeb 实现验证码功能(demo) 2024-04-14
