栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot Test 多线程报错:dataSource already closed

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 {
                    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  Future submitCallable(Callable callable) {
        Future submit = executor.submit(callable);
        return submit;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979044.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号