您好,登錄后才能下訂單哦!
本文主要給大家介紹了關(guān)于spring boot異步調(diào)用方式@Async的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面來一起看看詳細的介紹:
1.使用背景
在日常開發(fā)的項目中,當訪問其他人的接口較慢或者做耗時任務(wù)時,不想程序一直卡在耗時任務(wù)上,想程序能夠并行執(zhí)行,我們可以使用多線程來并行的處理任務(wù),也可以使用spring提供的異步處理方式@Async。
2.異步處理方式
3.@Async不返回數(shù)據(jù)
使用@EnableAsync啟用異步注解
@Configuration @EnableAsync @Slf4j public class AsyncConfig{ }
在異步處理的方法dealNoReturnTask上添加注解@Async
@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測試類:
@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é)果為:
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是為了模擬耗時任務(wù)
testDealNoReturnTask()
設(shè)置sleep 10s是為了確認異步是否執(zhí)行完成
4.@Async返回數(shù)據(jù)
異步調(diào)用返回數(shù)據(jù),F(xiàn)uture表示在未來某個點獲取執(zhí)行結(jié)果,返回數(shù)據(jù)類型可以自定義
@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é)束
@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é)果
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.異常處理
我們可以實現(xiàn)AsyncConfigurer接口,也可以繼承AsyncConfigurerSupport類來實現(xiàn)
在方法getAsyncExecutor()
中創(chuàng)建線程池的時候,必須使用 executor.initialize()
,不然在調(diào)用時會報線程池未初始化的異常。
如果使用threadPoolTaskExecutor()
來定義bean,則不需要初始化
@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(); } }
異步異常處理類:
@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(); } }
異步處理異常類:
@Data @AllArgsConstructor public class AsyncException extends Exception { private int code; private String errorMessage; }
handleUncaughtException()
會捕獲指定異常,原有任務(wù)還會繼續(xù)運行,直到結(jié)束。總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。