Springboot實現(xiàn)異步任務(wù)線程池代碼實例
異步任務(wù)線程池
異步任務(wù)線程池是一種用于處理異步任務(wù)的機制,它可以提高程序的并發(fā)性能和響應(yīng)速度。
通過將任務(wù)提交給線程池,線程池會自動管理線程的創(chuàng)建和銷毀,從而避免了頻繁創(chuàng)建和銷毀線程的開銷。
同時,線程池還可以控制并發(fā)線程的數(shù)量,避免資源過度占用。
異步任務(wù)線程池是多線程編程中常用的一種技術(shù),它可以應(yīng)用于各種場景,如網(wǎng)絡(luò)請求、數(shù)據(jù)庫操作、文件處理等。
1. 啟動類添加@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) { // 報警郵件,發(fā)短信等等 log.error("async task some Error: {} ,{} , {}", ex.getMessage(), method.getDeclaringClass().getName() + "." + method.getName(), Arrays.toString(params)); } }; } }
測試
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實現(xiàn)異步任務(wù)線程池代碼實例的文章就介紹到這了,更多相關(guān)Springboot異步任務(wù)線程池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java隨手筆記8之包、環(huán)境變量和訪問控制及maven profile實現(xiàn)多環(huán)境打包
這篇文章主要介紹了Java隨手筆記8之包、環(huán)境變量和訪問控制及maven profile實現(xiàn)多環(huán)境打包的相關(guān)資料,需要的朋友可以參考下2015-11-11Java邏輯運算符之&&、||?與&、?|的區(qū)別及應(yīng)用
這篇文章主要介紹了Java邏輯運算符之&&、||?與&、?|的區(qū)別及應(yīng)用的相關(guān)資料,分別是&&、||?與&、?|,并探討了它們在不同應(yīng)用場景中的表現(xiàn)和優(yōu)化效果,需要的朋友可以參考下2025-03-03Java多線程連續(xù)打印abc實現(xiàn)方法詳解
這篇文章主要介紹了Java多線程連續(xù)打印abc實現(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03基于Java編寫一個PDF與Word文件轉(zhuǎn)換工具
前段時間一直使用到word文檔轉(zhuǎn)pdf或者pdf轉(zhuǎn)word,尋思著用Java應(yīng)該是可以實現(xiàn)的,于是花了點時間寫了個文件轉(zhuǎn)換工具,感興趣的可以了解一下2023-01-01Java四舍五入時保留指定小數(shù)位數(shù)的五種方式
這篇文章主要介紹了Java四舍五入時保留指定小數(shù)位數(shù)的五種方式,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-09-09在Spring Data JPA中引入Querydsl的實現(xiàn)方式
這篇文章主要介紹了在Spring Data JPA中引入Querydsl的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01