SpringBoot Test 多线程报错

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot Test 多线程报错

、楽.   2022-06-20 我要评论

背景

使用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;
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们