都在建議,不要直接使用 @Async 注解,為什么?
@Async注解,在Spring體系中的應(yīng)用。本文僅說(shuō)明@Async注解的應(yīng)用規(guī)則,對(duì)于原理,調(diào)用邏輯,源碼分析,暫不介紹。對(duì)于異步方法調(diào)用,從Spring3開(kāi)始提供了@Async注解,該注解可以被標(biāo)注在方法上,以便異步地調(diào)用該方法。調(diào)用者將在調(diào)用時(shí)立即返回,方法的實(shí)際執(zhí)行將提交給Spring TaskExecutor的任務(wù)中,由指定的線(xiàn)程池中的線(xiàn)程執(zhí)行。@Async調(diào)用線(xiàn)程池,推薦使用自定義線(xiàn)程池的模式。自定義線(xiàn)程池常用方案:重新實(shí)現(xiàn)接口A(yíng)syncConfigurer。| 簡(jiǎn)介
應(yīng)用場(chǎng)景
SyncTaskExecutor:這個(gè)類(lèi)沒(méi)有實(shí)現(xiàn)異步調(diào)用,只是一個(gè)同步操作。只適用于不需要多線(xiàn)程的地方。
ThreadPoolTaskExecutor?:最常使用,推薦。其實(shí)質(zhì)是對(duì)java.util.concurrent.ThreadPoolExecutor的包裝。
異步的方法有:
| Spring中啟用@Async
//?基于Java配置的啟用方式:
@Configuration
@EnableAsync
public?class?SpringAsyncConfig?{?...?}
// Spring boot啟用:
@EnableAsync
@EnableTransactionManagement
public?class?SettlementApplication?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(SettlementApplication.class,?args);
????}
}
| @Async應(yīng)用默認(rèn)線(xiàn)程池
@Async注解在使用時(shí),不指定線(xiàn)程池的名稱(chēng)。查看源碼,@Async的默認(rèn)線(xiàn)程池為SimpleAsyncTaskExecutor。@Async無(wú)返回值調(diào)用,直接在使用類(lèi),使用方法(建議在使用方法)上,加上注解。若需要拋出異常,需手動(dòng)new一個(gè)異常拋出。/**
?????*?帶參數(shù)的異步調(diào)用?異步方法可以傳入?yún)?shù)
?????*??對(duì)于返回值是void,異常會(huì)被AsyncUncaughtExceptionHandler處理掉
?????*?@param?s
?????*/
????@Async
????public?void?asyncInvokeWithException(String?s)?{
????????log.info("asyncInvokeWithParameter,?parementer={}",?s);
????????throw?new?IllegalArgumentException(s);
????}
/**
?????*?異常調(diào)用返回Future
?????*??對(duì)于返回值是Future,不會(huì)被AsyncUncaughtExceptionHandler處理,需要我們?cè)诜椒ㄖ胁东@異常并處理
?????*??或者在調(diào)用方在調(diào)用Futrue.get時(shí)捕獲異常進(jìn)行處理
?????*
?????*?@param?i
?????*?@return
?????*/
????@Async
????public?Future?asyncInvokeReturnFuture(int?i)? {
????????log.info("asyncInvokeReturnFuture,?parementer={}",?i);
????????Future?future;
????????try?{
????????????Thread.sleep(1000?*?1);
????????????future?=?new?AsyncResult("success:"?+?i);
????????????throw?new?IllegalArgumentException("a");
????????}?catch?(InterruptedException?e)?{
????????????future?=?new?AsyncResult("error");
????????}?catch(IllegalArgumentException?e){
????????????future?=?new?AsyncResult("error-IllegalArgumentException");
????????}
????????return?future;
????}
stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.println())。它可能代表一個(gè)明確完成的Future,也有可能代表一個(gè)完成階段( CompletionStage ),它支持在計(jì)算完成以后觸發(fā)一些函數(shù)或執(zhí)行某些動(dòng)作。 它實(shí)現(xiàn)了Future和CompletionStage接口。
/**
?????*?數(shù)據(jù)查詢(xún)線(xiàn)程池
?????*/
????private?static?final?ThreadPoolExecutor?SELECT_POOL_EXECUTOR?=?new?ThreadPoolExecutor(10,?20,?5000,
????????????TimeUnit.MILLISECONDS,?new?LinkedBlockingQueue<>(1024),?new?ThreadFactoryBuilder().setNameFormat("selectThreadPoolExecutor-%d").build());
//?tradeMapper.countTradeLog(tradeSearchBean)方法表示,獲取數(shù)量,返回值為int
?//?獲取總條數(shù)
????????CompletableFuture?countFuture?=?CompletableFuture
????????????????.supplyAsync(()?->?tradeMapper.countTradeLog(tradeSearchBean),?SELECT_POOL_EXECUTOR);
//?同步阻塞
????CompletableFuture.allOf(countFuture).join();
//?獲取結(jié)果
?int?count?=?countFuture.get();
newFixedThreadPool和newSingleThreadExecutor:主要問(wèn)題是堆積的請(qǐng)求處理隊(duì)列可能會(huì)耗費(fèi)非常大的內(nèi)存,甚至OOM。 newCachedThreadPool和newScheduledThreadPool:要問(wèn)題是線(xiàn)程數(shù)最大數(shù)是 Integer.MAX_VALUE,可能會(huì)創(chuàng)建數(shù)量非常多的線(xiàn)程,甚至OOM。
concurrencyLimit>=0時(shí)開(kāi)啟限流機(jī)制,默認(rèn)關(guān)閉限流機(jī)制即concurrencyLimit=-1,當(dāng)關(guān)閉情況下,會(huì)不斷創(chuàng)建新的線(xiàn)程來(lái)處理任務(wù)。基于默認(rèn)配置,SimpleAsyncTaskExecutor并不是嚴(yán)格意義的線(xiàn)程池,達(dá)不到線(xiàn)程復(fù)用的功能。| @Async應(yīng)用自定義線(xiàn)程池
重新實(shí)現(xiàn)接口A(yíng)syncConfigurer; 繼承AsyncConfigurerSupport; 配置由自定義的TaskExecutor替代內(nèi)置的任務(wù)執(zhí)行器。
@Async的默認(rèn)調(diào)用規(guī)則,會(huì)優(yōu)先查詢(xún)?cè)创a中實(shí)現(xiàn)AsyncConfigurer這個(gè)接口的類(lèi),實(shí)現(xiàn)這個(gè)接口的類(lèi)為AsyncConfigurerSupport。但默認(rèn)配置的線(xiàn)程池和異步處理方法均為空,所以,無(wú)論是繼承或者重新實(shí)現(xiàn)接口,都需指定一個(gè)線(xiàn)程池。且重新實(shí)現(xiàn)?public Executor getAsyncExecutor()方法。@Configuration
?public?class?AsyncConfiguration?implements?AsyncConfigurer?{
?????@Bean("kingAsyncExecutor")
?????public?ThreadPoolTaskExecutor?executor()?{
?????????ThreadPoolTaskExecutor?executor?=?new?ThreadPoolTaskExecutor();
?????????int?corePoolSize?=?10;
?????????executor.setCorePoolSize(corePoolSize);
?????????int?maxPoolSize?=?50;
?????????executor.setMaxPoolSize(maxPoolSize);
?????????int?queueCapacity?=?10;
?????????executor.setQueueCapacity(queueCapacity);
?????????executor.setRejectedExecutionHandler(new?ThreadPoolExecutor.CallerRunsPolicy());
?????????String?threadNamePrefix?=?"kingDeeAsyncExecutor-";
?????????executor.setThreadNamePrefix(threadNamePrefix);
?????????executor.setWaitForTasksToCompleteOnShutdown(true);
?????????//?使用自定義的跨線(xiàn)程的請(qǐng)求級(jí)別線(xiàn)程工廠(chǎng)類(lèi)19?????????int?awaitTerminationSeconds?=?5;
?????????executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
?????????executor.initialize();
?????????return?executor;
?????}
?
?????@Override
?????public?Executor?getAsyncExecutor()?{
?????????return?executor();
?????}
?
?????@Override
?????public?AsyncUncaughtExceptionHandler?getAsyncUncaughtExceptionHandler()?{
?????????return?(ex,?method,?params)?->?ErrorLogger.getInstance().log(String.format("執(zhí)行異步任務(wù)'%s'",?method),?ex);
?????}
?}
@Configuration??
@EnableAsync??
class?SpringAsyncConfigurer?extends?AsyncConfigurerSupport?{??
??
????@Bean??
????public?ThreadPoolTaskExecutor?asyncExecutor()?{??
????????ThreadPoolTaskExecutor?threadPool?=?new?ThreadPoolTaskExecutor();??
????????threadPool.setCorePoolSize(3);??
????????threadPool.setMaxPoolSize(3);??
????????threadPool.setWaitForTasksToCompleteOnShutdown(true);??
????????threadPool.setAwaitTerminationSeconds(60?*?15);??
????????return?threadPool;??
????}??
??
????@Override??
????public?Executor?getAsyncExecutor()?{??
????????return?asyncExecutor;??
}??
??@Override??
????public?AsyncUncaughtExceptionHandler?getAsyncUncaughtExceptionHandler()?{
????return?(ex,?method,?params)?->?ErrorLogger.getInstance().log(String.format("執(zhí)行異步任務(wù)'%s'",?method),?ex);
}
}
beanFactory.getBean(TaskExecutor.class)先查看是否有線(xiàn)程池,未配置時(shí),通過(guò)beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class),又查詢(xún)是否存在默認(rèn)名稱(chēng)為T(mén)askExecutor的線(xiàn)程池。所以可以在項(xiàng)目中,定義名稱(chēng)為T(mén)askExecutor的bean生成一個(gè)默認(rèn)線(xiàn)程池。也可不指定線(xiàn)程池的名稱(chēng),申明一個(gè)線(xiàn)程池,本身底層是基于TaskExecutor.class便可。比如:Executor.class:ThreadPoolExecutorAdapter->ThreadPoolExecutor->AbstractExecutorService->ExecutorService->Executor
Executor.class,在替換默認(rèn)的線(xiàn)程池時(shí),需設(shè)置默認(rèn)的線(xiàn)程池名稱(chēng)為T(mén)askExecutor。TaskExecutor.class:ThreadPoolTaskExecutor->SchedulingTaskExecutor->AsyncTaskExecutor->TaskExecutor
TaskExecutor.class,在替換默認(rèn)的線(xiàn)程池時(shí),可不指定線(xiàn)程池名稱(chēng)。@EnableAsync
?@Configuration
?public?class?TaskPoolConfig?{
?????@Bean(name?=?AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
?????public?Executor?taskExecutor()?{
?????????ThreadPoolTaskExecutor?executor?=?new?ThreadPoolTaskExecutor();
??????????//核心線(xiàn)程池大小
?????????executor.setCorePoolSize(10);
?????????//最大線(xiàn)程數(shù)
?????????executor.setMaxPoolSize(20);
?????????//隊(duì)列容量
?????????executor.setQueueCapacity(200);
?????????//活躍時(shí)間
?????????executor.setKeepAliveSeconds(60);
?????????//線(xiàn)程名字前綴
?????????executor.setThreadNamePrefix("taskExecutor-");
?????????executor.setRejectedExecutionHandler(new?ThreadPoolExecutor.CallerRunsPolicy());
?????????return?executor;
?????}
????@Bean(name?=?"new_task")
?????public?Executor?taskExecutor()?{
?????????ThreadPoolTaskExecutor?executor?=?new?ThreadPoolTaskExecutor();
??????????//核心線(xiàn)程池大小
?????????executor.setCorePoolSize(10);
?????????//最大線(xiàn)程數(shù)
?????????executor.setMaxPoolSize(20);
?????????//隊(duì)列容量
?????????executor.setQueueCapacity(200);
?????????//活躍時(shí)間
?????????executor.setKeepAliveSeconds(60);
?????????//線(xiàn)程名字前綴
?????????executor.setThreadNamePrefix("taskExecutor-");
?????????executor.setRejectedExecutionHandler(new?ThreadPoolExecutor.CallerRunsPolicy());
?????????return?executor;
?????}
?}
@Async注解,使用系統(tǒng)默認(rèn)或者自定義的線(xiàn)程池(代替默認(rèn)線(xiàn)程池)。可在項(xiàng)目中設(shè)置多個(gè)線(xiàn)程池,在異步調(diào)用時(shí),指明需要調(diào)用的線(xiàn)程池名稱(chēng),如@Async("new_task")。| @Async部分重要源碼解析

getAsyncExecutor()時(shí),可以設(shè)置默認(rèn)的線(xiàn)程池。



評(píng)論
圖片
表情
