SpringBoot Test 多線程報錯的根本原因(dataSource already closed)
背景
使用Springboot test進行相關(guān)測試的時候,發(fā)現(xiàn)開啟線程操作數(shù)據(jù)庫的時候異常。
排查方法
將線程移除,采用并行的方式,操作數(shù)據(jù)庫正常。
根本原因
- SpringBoot Test 主線程退出,導(dǎo)致Spring 容器關(guān)閉。
- Spring容器關(guān)閉,導(dǎo)致DruidDataSource 關(guān)閉
- 此時用戶線程去訪問已關(guān)閉的數(shù)據(jù)源,導(dǎo)致報錯。
解決方法
提供一個全局的線程池,然后使用線程池開啟線程操作,然后添加監(jiān)聽器,監(jiān)聽線程池里面是否有未完成的任務(wù),如果有則不關(guān)閉容器。
@Component
public class EventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextClosedEvent) {
LoggerClient.info("容器即將關(guān)閉");
//線程池工具類
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;
}
}到此這篇關(guān)于SpringBoot Test 多線程報錯:dataSource already closed的文章就介紹到這了,更多相關(guān)SpringBoot Test 多線程報錯內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java基礎(chǔ)高級綜合練習(xí)題撲克牌的創(chuàng)建
今天小編就為大家分享一篇關(guān)于Java基礎(chǔ)高級綜合練習(xí)題撲克牌的創(chuàng)建,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Java實現(xiàn)幾十萬條數(shù)據(jù)插入實例教程(30萬條數(shù)據(jù)插入MySQL僅需13秒)
這篇文章主要給大家介紹了關(guān)于Java如何實現(xiàn)幾十萬條數(shù)據(jù)插入的相關(guān)資料,30萬條數(shù)據(jù)插入MySQL僅需13秒,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-04-04
spring boot2.0實現(xiàn)優(yōu)雅停機的方法
這篇文章主要介紹了spring boot2.0實現(xiàn)優(yōu)雅停機的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Mybatis-plus3.4.3下使用lambdaQuery報錯解決
最近在使用lambdaQuery().eq(CommonUser::getOpenId, openId).one()進行查詢報錯,本文主要介紹了Mybatis-plus3.4.3下使用lambdaQuery報錯解決,具有一定的參考價值,感興趣的可以了解一下2024-07-07
Tomcat正常啟動,訪問所有頁面均報404異常,404異??偨Y(jié)分析
今天遇到一個問題:Tomcat正常啟動,訪問所有頁面均報404異常,究竟該如何解決這個問題呢?下邊小編將為大家介紹一下解決方法,需要的朋友可以參考下2013-07-07

