SpringBoot Test 多线程报错的根本原因(dataSource already closed)

网友投稿 1002 2022-09-27

SpringBoot Test 多线程报错的根本原因(dataSource already closed)

SpringBoot Test 多线程报错的根本原因(dataSource already closed)

背景

使用Springboot test进行相关测试的时候,发现开启线程操作数据库的时候异常。

排查方法

将线程移除,采用并行的方式,操作数据库正常。

根本原因

SpringBoot Test 主线程退出,导致Spring 容器关闭。Spring容器关闭,导致DruidDataSource 关闭此时用户线程去访问已关闭的数据源,导致报错。

解决方法

提供一个全局的线程池,然后使用线程池开启线程操作,然后添加-,监听线程池里面是否有未完成的任务,如果有则不关闭容器。

@Component

public class EventListener implements ApplicationListener {

@Override

public void onApplicationEvent(ApplicationEvent event) {

if (event instanceof ContextClosedEvent) {

LoggerClient.info("容器即将关闭");

//线程池工具类

ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil();

while (threadPoolUtil.getExecutor().isTerminated()) {

try {

Cldnrj Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

​public class ThreadPoolUtil {

private static final ExecutorService exechttp://utor = 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 callable) {

Future submit = executor.submit(callable);

return submit;

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Redis AOF文件校验
下一篇:Nginx http_secure_link_module 实现下载防盗链
相关文章

 发表评论

暂时没有评论,来抢沙发吧~