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



