在使用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)


基础教程推荐
猜你喜欢
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- Java File类的概述及常用方法使用详解 2023-05-18
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- JVM分析之类加载机制详解 2023-04-06
- 工厂方法在Spring框架中的运用 2023-06-23
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- 全局记录Feign的请求和响应日志方式 2023-01-09
- Project Reactor源码解析publishOn使用示例 2023-04-12
- 用java实现扫雷游戏 2022-12-06