本文主要給大家介紹了關(guān)于spring boot異步調(diào)用方式@Async的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面來一起看看詳細(xì)的介紹:
1.使用背景
在日常開發(fā)的項(xiàng)目中,當(dāng)訪問其他人的接口較慢或者做耗時(shí)任務(wù)時(shí),不想程序一直卡在耗時(shí)任務(wù)上,想程序能夠并行執(zhí)行,我們可以使用多線程來并行的處理任務(wù),也可以使用spring提供的異步處理方式@Async。
2.異步處理方式
- 調(diào)用之后,不返回任何數(shù)據(jù)。
- 調(diào)用之后,返回?cái)?shù)據(jù),通過Future來獲取返回?cái)?shù)據(jù)
3.@Async不返回?cái)?shù)據(jù)
使用@EnableAsync啟用異步注解
1
2
3
4
5
|
@Configuration @EnableAsync @Slf4j public class AsyncConfig{ } |
在異步處理的方法dealNoReturnTask上添加注解@Async
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Component @Slf4j public class AsyncTask { @Async public void dealNoReturnTask(){ log.info( "Thread {} deal No Return Task start" , Thread.currentThread().getName()); try { Thread.sleep( 3000 ); } catch (InterruptedException e) { e.printStackTrace(); } log.info( "Thread {} deal No Return Task end at {}" , Thread.currentThread().getName(), System.currentTimeMillis()); } } |
Test測試類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@SpringBootTest (classes = SpringbootApplication. class ) @RunWith (SpringJUnit4ClassRunner. class ) @Slf4j public class AsyncTest { @Autowired private AsyncTask asyncTask; @Test public void testDealNoReturnTask(){ asyncTask.dealNoReturnTask(); try { log.info( "begin to deal other Task!" ); Thread.sleep( 10000 ); } catch (InterruptedException e) { e.printStackTrace(); } } |
日志打印結(jié)果為:
1
2
3
|
begin to deal other Task! AsyncExecutorThread-1 deal No Return Task start AsyncExecutorThread-1 deal No Return Task end at 1499751227034 |
從日志中我們可以看出,方法dealNoReturnTask()
是異步執(zhí)行完成的。
dealNoReturnTask()
設(shè)置sleep 3s是為了模擬耗時(shí)任務(wù)
testDealNoReturnTask()
設(shè)置sleep 10s是為了確認(rèn)異步是否執(zhí)行完成
4.@Async返回?cái)?shù)據(jù)
異步調(diào)用返回?cái)?shù)據(jù),F(xiàn)uture表示在未來某個(gè)點(diǎn)獲取執(zhí)行結(jié)果,返回?cái)?shù)據(jù)類型可以自定義
1
2
3
4
5
6
7
8
9
10
11
12
|
@Async public Future<String> dealHaveReturnTask() { try { Thread.sleep( 3000 ); } catch (InterruptedException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(); jsonObject.put( "thread" , Thread.currentThread().getName()); jsonObject.put( "time" , System.currentTimeMillis()); return new AsyncResult<String>(jsonObject.toJSONString()); } |
測試類用isCancelled判斷異步任務(wù)是否取消,isDone判斷任務(wù)是否執(zhí)行結(jié)束
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@Test public void testDealHaveReturnTask() throws Exception { Future<String> future = asyncTask.dealHaveReturnTask(); log.info( "begin to deal other Task!" ); while ( true ) { if (future.isCancelled()){ log.info( "deal async task is Cancelled" ); break ; } if (future.isDone() ) { log.info( "deal async task is Done" ); log.info( "return result is " + future.get()); break ; } log.info( "wait async task to end ..." ); Thread.sleep( 1000 ); } } |
日志打印如下,我們可以看出任務(wù)一直在等待異步任務(wù)執(zhí)行完畢,用future.get()
來獲取異步任務(wù)的返回結(jié)果
1
2
3
4
5
6
7
|
begin to deal other Task! wait async task to end ... wait async task to end ... wait async task to end ... wait async task to end ... deal async task is Done return result is {"thread":"AsyncExecutorThread-1","time":1499752617330} |
4.異常處理
我們可以實(shí)現(xiàn)AsyncConfigurer接口,也可以繼承AsyncConfigurerSupport類來實(shí)現(xiàn)
在方法getAsyncExecutor()
中創(chuàng)建線程池的時(shí)候,必須使用 executor.initialize()
,不然在調(diào)用時(shí)會(huì)報(bào)線程池未初始化的異常。
如果使用threadPoolTaskExecutor()
來定義bean,則不需要初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
@Configuration @EnableAsync @Slf4j public class AsyncConfig implements AsyncConfigurer { // @Bean // public ThreadPoolTaskExecutor threadPoolTaskExecutor(){ // ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // executor.setCorePoolSize(10); // executor.setMaxPoolSize(100); // executor.setQueueCapacity(100); // return executor; // } @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize( 10 ); executor.setMaxPoolSize( 100 ); executor.setQueueCapacity( 100 ); executor.setThreadNamePrefix( "AsyncExecutorThread-" ); executor.initialize(); //如果不初始化,導(dǎo)致找到不到執(zhí)行器 return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new AsyncExceptionHandler(); } } |
異步異常處理類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Slf4j public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler { @Override public void handleUncaughtException(Throwable ex, Method method, Object... params) { log.info( "Async method: {} has uncaught exception,params:{}" , method.getName(), JSON.toJSONString(params)); if (ex instanceof AsyncException) { AsyncException asyncException = (AsyncException) ex; log.info( "asyncException:{}" ,asyncException.getErrorMessage()); } log.info( "Exception :" ); ex.printStackTrace(); } } |
異步處理異常類:
1
2
3
4
5
6
|
@Data @AllArgsConstructor public class AsyncException extends Exception { private int code; private String errorMessage; } |
-
在無返回值的異步調(diào)用中,異步處理拋出異常,AsyncExceptionHandler的
handleUncaughtException()
會(huì)捕獲指定異常,原有任務(wù)還會(huì)繼續(xù)運(yùn)行,直到結(jié)束。 - 在有返回值的異步調(diào)用中,異步處理拋出異常,會(huì)直接拋出異常,異步任務(wù)結(jié)束,原有處理結(jié)束執(zhí)行。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000010142962