SpringBoot Test 多線程報錯的根本原因(dataSource already closed)
背景
使用Springboot test進行相關測試的時候,發(fā)現(xiàn)開啟線程操作數(shù)據(jù)庫的時候異常。
排查方法
將線程移除,采用并行的方式,操作數(shù)據(jù)庫正常。
根本原因
- SpringBoot Test 主線程退出,導致Spring 容器關閉。
- Spring容器關閉,導致DruidDataSource 關閉
- 此時用戶線程去訪問已關閉的數(shù)據(jù)源,導致報錯。
解決方法
提供一個全局的線程池,然后使用線程池開啟線程操作,然后添加監(jiān)聽器,監(jiān)聽線程池里面是否有未完成的任務,如果有則不關閉容器。
@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; } }
到此這篇關于SpringBoot Test 多線程報錯:dataSource already closed的文章就介紹到這了,更多相關SpringBoot Test 多線程報錯內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決IDEA中多模塊下Mybatis逆向工程不生成相應文件的情況
這篇文章主要介紹了解決IDEA中多模塊下Mybatis逆向工程不生成相應文件的情況,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01springboot默認文件緩存(easy-captcha?驗證碼)
這篇文章主要介紹了springboot的文件緩存(easy-captcha?驗證碼),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06基于Spring Data的AuditorAware審計功能的示例代碼
這篇文章主要介紹了基于Spring Data的AuditorAware審計功能的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03