SpringBoot @Async如何自定義線程池及使用教程
更新時間:2024年01月22日 15:08:31 作者:知識淺談
這篇文章主要介紹了SpringBoot @Async如何自定義線程池及使用教程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
看別的教程一大堆廢話,直接上干貨不行嗎,直接看下邊例子
??配置異步線程池
@EnableAsync
@Configuration
public class AsyncConfiguration {
//定義線程池
@Bean("threadPool1") // bean的名稱,線程池的bean的名字,不是創(chuàng)建線程的名字
public Executor ThreadPool1(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); /** 核心線程數(shù)(默認線程數(shù)) */
executor.setMaxPoolSize(20);/** 最大線程數(shù) */
executor.setQueueCapacity(500);/** 緩沖隊列大小 */
executor.setKeepAliveSeconds(60);/** 允許線程空閑時間(單位:默認為秒) */
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("task-thread-"); /** 線程池名前綴 */
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); //拒絕策略:緩存隊列滿了之后由調用線程處理,一般是主線程
executor.initialize();
return executor;
}
}??異步方法
@RestController("/test")
public class Test2Controller {
@Async("threadPool1")
public void test1() throws InterruptedException {
Thread.sleep(5000);
System.out.println("test1");
}
}??調用異步方法
@Api("測試")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController
{
@Autowired
private Test2Controller test2Controller;
@ApiOperation("異步")
@GetMapping("/testAsync")
public String testAsync() throws InterruptedException {
test2Controller.test1();
return "async";
}
}結果:
結果直接返回:test1 5秒后打印出來。

??總結
到此這篇關于SpringBoot @Async如何自定義線程池以及使用教程的文章就介紹到這了,更多相關SpringBoot @Async自定義線程池內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring集成Web環(huán)境與SpringMVC組件的擴展使用詳解
這篇文章主要介紹了Spring集成Web環(huán)境與SpringMVC組件,它是一個MVC架構,用來簡化基于MVC架構的Web應用開發(fā)。SpringMVC最重要的就是五大組件2022-08-08
websocket在springboot+vue中的使用教程
這篇文章主要介紹了websocket在springboot+vue中的使用教程,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08
Java調用ChatGPT(基于SpringBoot和Vue)實現(xiàn)可連續(xù)對話和流式輸出的ChatGPT API
這篇文章主要介紹了Java調用ChatGPT(基于SpringBoot和Vue),實現(xiàn)可連續(xù)對話和流式輸出的ChatGPT API(可自定義實現(xiàn)AI助手),文中代碼示例介紹的非常詳細,感興趣的朋友可以參考下2023-04-04
SpringSecurity顯示用戶賬號已被鎖定的原因及解決方案
SpringSecurity中用戶賬號被鎖定問題源于UserDetails接口方法返回值錯誤,解決方案是修正isAccountNonLocked()等方法的邏輯,確保返回正確狀態(tài),避免誤判賬戶鎖定,從而允許合法用戶登錄,下面給大家介紹SpringSecurity顯示用戶賬號已被鎖定的解決方案,感興趣的朋友一起看看吧2025-06-06
Spring Boot中@ConditionalOnProperty的使用方法
這篇文章主要給大家介紹了關于Spring Boot中@ConditionalOnProperty的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用Spring Boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-12-12

