背景

使用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;
    }
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。