iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBootTest多线程报错的根本原因(dataSourcealreadyclosed)
  • 458
分享到

SpringBootTest多线程报错的根本原因(dataSourcealreadyclosed)

2024-04-02 19:04:59 458人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

背景 使用SpringBoot test进行相关测试的时候,发现开启线程操作数据库的时候异常。 排查方法 将线程移除,采用并行的方式,操作数据库正常。 根本原因 springBoot

背景

使用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 多线程报错内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBootTest多线程报错的根本原因(dataSourcealreadyclosed)

本文链接: https://www.lsjlt.com/news/151858.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作