SpringBoot Test 多線程報(bào)錯(cuò)的根本原因(dataSource already closed)
背景
使用Springboot test進(jìn)行相關(guān)測(cè)試的時(shí)候,發(fā)現(xiàn)開(kāi)啟線程操作數(shù)據(jù)庫(kù)的時(shí)候異常。
排查方法
將線程移除,采用并行的方式,操作數(shù)據(jù)庫(kù)正常。
根本原因
- SpringBoot Test 主線程退出,導(dǎo)致Spring 容器關(guān)閉。
- Spring容器關(guān)閉,導(dǎo)致DruidDataSource 關(guān)閉
- 此時(shí)用戶線程去訪問(wèn)已關(guān)閉的數(shù)據(jù)源,導(dǎo)致報(bào)錯(cuò)。
解決方法
提供一個(gè)全局的線程池,然后使用線程池開(kāi)啟線程操作,然后添加監(jiān)聽(tīng)器,監(jiān)聽(tīng)線程池里面是否有未完成的任務(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 多線程報(bào)錯(cuò):dataSource already closed的文章就介紹到這了,更多相關(guān)SpringBoot Test 多線程報(bào)錯(cuò)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot使用ThreadPoolTaskExecutor多線程批量插入百萬(wàn)級(jí)數(shù)據(jù)的實(shí)現(xiàn)方法
- SpringBoot ThreadLocal實(shí)現(xiàn)公共字段自動(dòng)填充案例講解
- SpringBoot通過(guò)ThreadLocal實(shí)現(xiàn)登錄攔截詳解流程
- springboot使用線程池(ThreadPoolTaskExecutor)示例
- IDEA2020.2創(chuàng)建springboot項(xiàng)目卡死在reading maven project的問(wèn)題
- SpringBoot實(shí)現(xiàn)Read Through模式的操作過(guò)程
相關(guān)文章
JAVA泛型的繼承和實(shí)現(xiàn)、擦除原理解析
這篇文章主要介紹了JAVA泛型的繼承和實(shí)現(xiàn)、擦除原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
解決IDEA中多模塊下Mybatis逆向工程不生成相應(yīng)文件的情況
這篇文章主要介紹了解決IDEA中多模塊下Mybatis逆向工程不生成相應(yīng)文件的情況,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01
springboot默認(rèn)文件緩存(easy-captcha?驗(yàn)證碼)
這篇文章主要介紹了springboot的文件緩存(easy-captcha?驗(yàn)證碼),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
基于Spring Data的AuditorAware審計(jì)功能的示例代碼
這篇文章主要介紹了基于Spring Data的AuditorAware審計(jì)功能的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03

