Spring Boot異步調(diào)用@Async過程詳解
在實際開發(fā)中,有時候為了及時處理請求和進行響應(yīng),我們可能會多任務(wù)同時執(zhí)行,或者先處理主任務(wù),也就是異步調(diào)用,異步調(diào)用的實現(xiàn)有很多,例如多線程、定時任務(wù)、消息隊列等,
我們來講講@Async異步方法調(diào)用。
一、@Async使用演示
@Async是Spring內(nèi)置注解,用來處理異步任務(wù),在SpringBoot中同樣適用,且在SpringBoot項目中,除了boot本身的starter外,不需要額外引入依賴。
而要使用@Async,需要在啟動類上加上@EnableAsync主動聲明來開啟異步方法。
@EnableAsync @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
現(xiàn)假設(shè)有3個任務(wù)需要去處理,分別對應(yīng)AsyncTask類的taskOne、taskTwo、taskThree方法,這里做了線程的sleep來模擬實際運行。
@Slf4j @Component public class AsyncTask { private Random random = new Random(); public void taskOne() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)一執(zhí)行完成耗時{}秒", (end - start)/1000f); } public void taskTwo() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)二執(zhí)行完成耗時{}秒", (end - start)/1000f); } public void taskThree() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)三執(zhí)行完成耗時{}秒", (end - start)/1000f); } }
然后編寫測試類,由于@Async注解需要再Spring容器啟動后才能生效,所以這里講測試類放到了SpringBoot的test包下,使用了SpringBootTest。
@Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootApplication.class) public class AsyncTaskTest { @Autowired private AsyncTask asyncTask; @Test public void doAsyncTasks(){ try { long start = System.currentTimeMillis(); asyncTask.taskOne(); asyncTask.taskTwo(); asyncTask.taskThree(); Thread.sleep(5000); long end = System.currentTimeMillis(); log.info("主程序執(zhí)行完成耗時{}秒", (end - start)/1000f); } catch (InterruptedException e) { e.printStackTrace(); } } }
運行測試方法,可以在控制臺看到任務(wù)一二三按順序執(zhí)行,最后主程序完成,這和我們的預(yù)期一樣,因為我們沒有任何額外的處理,他們就是普通的方法,按編碼順序依次執(zhí)行。
而如果要使任務(wù)并發(fā)執(zhí)行,我們只需要在任務(wù)方法上使用@Async注解即可,需要注意的是@Async所修飾的方法不要定義為static類型,這樣異步調(diào)用不會生效。
@Slf4j @Component public class AsyncTask { private Random random = new Random(); //@Async所修飾的函數(shù)不要定義為static類型,這樣異步調(diào)用不會生效 @Async public void taskOne() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)一執(zhí)行完成耗時{}秒", (end - start)/1000f); } @Async public void taskTwo() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)二執(zhí)行完成耗時{}秒", (end - start)/1000f); } @Async public void taskThree() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)三執(zhí)行完成耗時{}秒", (end - start)/1000f); } }
然后我們在運行測試類,這個時候輸出可能就五花八門了,任意任務(wù)都可能先執(zhí)行完成,也有可能有的方法因為主程序關(guān)閉而沒有輸出。
二、Future獲取異步執(zhí)行結(jié)果
上面演示了@Async,但是有時候除了需要任務(wù)并發(fā)調(diào)度外,我們還需要獲取任務(wù)的返回值,且在多任務(wù)都執(zhí)行完成后再結(jié)束主任務(wù),這個時候又該怎么處理呢?
在多線程里通過Callable和Future可以獲取返回值,這里也是類似的,我們使用Future返回方法的執(zhí)行結(jié)果,AsyncResult是Future的一個實現(xiàn)類。
@Slf4j @Component public class FutureTask { private Random random = new Random(); //@Async所修飾的函數(shù)不要定義為static類型,這樣異步調(diào)用不會生效 @Async public Future<String> taskOne() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)一執(zhí)行完成耗時{}秒", (end - start)/1000f); return new AsyncResult <>("任務(wù)一Ok"); } @Async public Future<String> taskTwo() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)二執(zhí)行完成耗時{}秒", (end - start)/1000f); return new AsyncResult <>("任務(wù)二OK"); } @Async public Future<String> taskThree() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("任務(wù)三執(zhí)行完成耗時{}秒", (end - start)/1000f); return new AsyncResult <>("任務(wù)三Ok"); } }
在AsyncResult中:
- isDone()方法可以用于判斷異步方法是否執(zhí)行完成,若任務(wù)完成,則返回true
- get()方法可用于獲取任務(wù)執(zhí)行后返回的結(jié)果
- cancel(boolean mayInterruptIfRunning)可用于取消任務(wù),參數(shù)mayInterruptIfRunning表示是否允許取消正在執(zhí)行卻沒有執(zhí)行完畢的任務(wù),如果設(shè)置true,則表示可以取消正在執(zhí)行過程中的任務(wù)
- isCancelled()方法表示任務(wù)是否被取消成功,如果在任務(wù)正常完成前被取消成功,則返回 true
- get(long timeout, TimeUnit unit)用來獲取執(zhí)行結(jié)果,如果在指定時間內(nèi),還沒獲取到結(jié)果,就直接返回null
@Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootApplication.class) public class AsyncTaskTest { @Autowired private FutureTask futureTask; @Test public void doFutureTasks(){ try { long start = System.currentTimeMillis(); Future <String> future1 = futureTask.taskOne(); Future <String> future2 = futureTask.taskTwo(); Future <String> future3 = futureTask.taskThree(); //3個任務(wù)執(zhí)行完成之后再執(zhí)行主程序 do { Thread.sleep(100); } while (future1.isDone() && future2.isDone() && future3.isDone()); log.info("獲取異步方法的返回值:{}", future1.get()); Thread.sleep(5000); long end = System.currentTimeMillis(); log.info("主程序執(zhí)行完成耗時{}秒", (end - start)/1000f); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
運行測試類,我們可以看到任務(wù)一二三異步執(zhí)行了,主任務(wù)最后執(zhí)行完成,而且可以獲取到任務(wù)的返回信息。
源碼地址:https://github.com/imyanger/springboot-project/tree/master/p23-springboot-async
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Get方式提交數(shù)據(jù)到Tomcat服務(wù)器的方法
這篇文章將介紹向服務(wù)器發(fā)送數(shù)據(jù),并且服務(wù)器將數(shù)據(jù)的處理結(jié)果返回給客戶端,本文給大家介紹使用Get方式向服務(wù)器發(fā)送數(shù)據(jù),感興趣的朋友一起學(xué)習(xí)吧2016-04-04Java中SpringSecurity密碼錯誤5次鎖定用戶的實現(xiàn)方法
這篇文章主要介紹了Java中SpringSecurity密碼錯誤5次鎖定用戶的實現(xiàn)方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03Java?實現(xiàn)訂單未支付超時自動取消功能(京東商城為例)
本文以京東網(wǎng)上商城為例,給大家介紹商品在下單后沒有支付的情況下,超時自動取消功能,超過24小時,就會自動取消訂單,下面使用 Java 定時器實現(xiàn)超時取消訂單功能,感興趣的朋友一起看看吧2022-01-01Mybatis中注入執(zhí)行sql查詢、更新、新增及建表語句案例代碼
這篇文章主要介紹了Mybatis中注入執(zhí)行sql查詢、更新、新增以及建表語句,主要說明一個另類的操作,注入sql,并使用mybatis執(zhí)行,結(jié)合案例代碼詳解講解,需要的朋友可以參考下2023-02-02使用純Java實現(xiàn)一個WebSSH項目的示例代碼
這篇文章主要介紹了使用純Java實現(xiàn)一個WebSSH項目,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03