Springboot實(shí)現(xiàn)異步任務(wù)線程池代碼實(shí)例
異步任務(wù)線程池
異步任務(wù)線程池是一種用于處理異步任務(wù)的機(jī)制,它可以提高程序的并發(fā)性能和響應(yīng)速度。
通過(guò)將任務(wù)提交給線程池,線程池會(huì)自動(dòng)管理線程的創(chuàng)建和銷毀,從而避免了頻繁創(chuàng)建和銷毀線程的開(kāi)銷。
同時(shí),線程池還可以控制并發(fā)線程的數(shù)量,避免資源過(guò)度占用。
異步任務(wù)線程池是多線程編程中常用的一種技術(shù),它可以應(yīng)用于各種場(chǎng)景,如網(wǎng)絡(luò)請(qǐng)求、數(shù)據(jù)庫(kù)操作、文件處理等。
1. 啟動(dòng)類添加@EnableAsync注解
package com.gblfy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class JavaEscapeApplication { public static void main(String[] args) { SpringApplication.run(JavaEscapeApplication.class, args); } }
2. 異步方法添加@Async注解
package com.gblfy.async_task; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import java.util.concurrent.Future; @Slf4j @Service public class AsyncService { @Async public void asyncProcess01() throws Exception { log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName()); Thread.sleep(2000); log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName()); } @Async public Future<String> asyncProcess02() throws Exception { log.info("AsyncService Start to asyncProcess02->{}", Thread.currentThread().getName()); Thread.sleep(2000); log.info("AsyncService Done to asyncProcess02->{}", Thread.currentThread().getName()); return new AsyncResult<>("imooc"); } @Async public void asyncProcess03() { log.info("AsyncService Start to asyncProcess03->{}", Thread.currentThread().getName()); throw new RuntimeException("throw exception asyncProcess03"); } }
3. 自定義線程池以及線程池異常策略
package com.gblfy.async_task; import lombok.extern.slf4j.Slf4j; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; /** * 自定義異步任務(wù)線程池 */ @Slf4j @Configuration public class AsyncTaskConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("cmiip-"); executor.setCorePoolSize(15); executor.setMaxPoolSize(20); executor.setKeepAliveSeconds(5); executor.setQueueCapacity(100); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new AsyncUncaughtExceptionHandler() { @Override public void handleUncaughtException(Throwable ex, Method method, Object... params) { // 報(bào)警郵件,發(fā)短信等等 log.error("async task some Error: {} ,{} , {}", ex.getMessage(), method.getDeclaringClass().getName() + "." + method.getName(), Arrays.toString(params)); } }; } }
測(cè)試
package com.gblfy.async_task; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @Slf4j @SpringBootTest class AsyncServiceTest { @Autowired private AsyncService asyncService; @Test void contextLoads() throws Exception { // asyncService.asyncProcess01(); Future<String> future= asyncService.asyncProcess02(); log.info("Async Process02 return :->{}", future.get(1, TimeUnit.SECONDS)); } @Test void contextLoads2() throws Exception { asyncService.asyncProcess03(); Thread.sleep(3000); } }
到此這篇關(guān)于Springboot實(shí)現(xiàn)異步任務(wù)線程池代碼實(shí)例的文章就介紹到這了,更多相關(guān)Springboot異步任務(wù)線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java隨手筆記8之包、環(huán)境變量和訪問(wèn)控制及maven profile實(shí)現(xiàn)多環(huán)境打包
這篇文章主要介紹了Java隨手筆記8之包、環(huán)境變量和訪問(wèn)控制及maven profile實(shí)現(xiàn)多環(huán)境打包的相關(guān)資料,需要的朋友可以參考下2015-11-11Java邏輯運(yùn)算符之&&、||?與&、?|的區(qū)別及應(yīng)用
這篇文章主要介紹了Java邏輯運(yùn)算符之&&、||?與&、?|的區(qū)別及應(yīng)用的相關(guān)資料,分別是&&、||?與&、?|,并探討了它們?cè)诓煌瑧?yīng)用場(chǎng)景中的表現(xiàn)和優(yōu)化效果,需要的朋友可以參考下2025-03-03SpringBoot配置攔截器實(shí)現(xiàn)過(guò)程詳解
在系統(tǒng)中經(jīng)常需要在處理用戶請(qǐng)求之前和之后執(zhí)行一些行為,例如檢測(cè)用戶的權(quán)限,或者將請(qǐng)求的信息記錄到日志中,即平時(shí)所說(shuō)的"權(quán)限檢測(cè)"及"日志記錄",下面這篇文章主要給大家介紹了關(guān)于在SpringBoot項(xiàng)目中整合攔截器的相關(guān)資料,需要的朋友可以參考下2022-10-10java Lombok之@Accessors用法及說(shuō)明
這篇文章主要介紹了java Lombok之@Accessors用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03Java多線程連續(xù)打印abc實(shí)現(xiàn)方法詳解
這篇文章主要介紹了Java多線程連續(xù)打印abc實(shí)現(xiàn)方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03基于Java編寫一個(gè)PDF與Word文件轉(zhuǎn)換工具
前段時(shí)間一直使用到word文檔轉(zhuǎn)pdf或者pdf轉(zhuǎn)word,尋思著用Java應(yīng)該是可以實(shí)現(xiàn)的,于是花了點(diǎn)時(shí)間寫了個(gè)文件轉(zhuǎn)換工具,感興趣的可以了解一下2023-01-01Java四舍五入時(shí)保留指定小數(shù)位數(shù)的五種方式
這篇文章主要介紹了Java四舍五入時(shí)保留指定小數(shù)位數(shù)的五種方式,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-09-09在Spring Data JPA中引入Querydsl的實(shí)現(xiàn)方式
這篇文章主要介紹了在Spring Data JPA中引入Querydsl的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01