什么是“異步呼叫”?“異步呼叫”對應的是“同步呼叫”,同步呼叫指程式按照定義順序依次執行,每一行程式都必須等待上一行程式執行完成之后才能執行;異步呼叫指程式在順序執行時,不等待異步呼叫的陳述句回傳結果就執行后面的程式,
同步呼叫
下面通過一個簡單示例來直觀的理解什么是同步呼叫:
定義Task類,創建三個處理函式分別模擬三個執行任務的操作,操作消耗時間隨機取(10秒內)
@Slf4j
@Component
public class AsyncTasks {
public static Random random = new Random();
public void doTaskOne() throws Exception {
log.info("開始做任務一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務一,耗時:" + (end - start) + "毫秒");
}
public void doTaskTwo() throws Exception {
log.info("開始做任務二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務二,耗時:" + (end - start) + "毫秒");
}
public void doTaskThree() throws Exception {
log.info("開始做任務三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務三,耗時:" + (end - start) + "毫秒");
}
}
在單元測驗用例中,注入Task物件,并在測驗用例中執行doTaskOne、doTaskTwo、doTaskThree三個函式,
@Slf4j
@SpringBootTest
public class Chapter75ApplicationTests {
@Autowired
private AsyncTasks asyncTasks;
@Test
public void test() throws Exception {
asyncTasks.doTaskOne();
asyncTasks.doTaskTwo();
asyncTasks.doTaskThree();
}
}
執行單元測驗,可以看到類似如下輸出:
2021-09-11 23:19:12.922 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 開始做任務一
2021-09-11 23:19:17.788 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 完成任務一,耗時:4865毫秒
2021-09-11 23:19:17.788 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 開始做任務二
2021-09-11 23:19:24.851 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 完成任務二,耗時:7063毫秒
2021-09-11 23:19:24.851 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 開始做任務三
2021-09-11 23:19:26.928 INFO 92539 --- [ main] com.didispace.chapter75.AsyncTasks : 完成任務三,耗時:2076毫秒
任務一、任務二、任務三順序的執行完了,換言之doTaskOne、doTaskTwo、doTaskThree三個函式順序的執行完成,
異步呼叫
上述的同步呼叫雖然順利的執行完了三個任務,但是可以看到執行時間比較長,若這三個任務本身之間不存在依賴關系,可以并發執行的話,同步呼叫在執行效率方面就比較差,可以考慮通過異步呼叫的方式來并發執行,
在Spring Boot中,我們只需要通過使用@Async注解就能簡單的將原來的同步函式變為異步函式,Task類改在為如下模式:
@Slf4j
@Component
public class AsyncTasks {
public static Random random = new Random();
@Async
public void doTaskOne() throws Exception {
log.info("開始做任務一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務一,耗時:" + (end - start) + "毫秒");
}
@Async
public void doTaskTwo() throws Exception {
log.info("開始做任務二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務二,耗時:" + (end - start) + "毫秒");
}
@Async
public void doTaskThree() throws Exception {
log.info("開始做任務三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務三,耗時:" + (end - start) + "毫秒");
}
}
為了讓@Async注解能夠生效,還需要在Spring Boot的主程式中配置@EnableAsync,如下所示:
@EnableAsync
@SpringBootApplication
public class Chapter75Application {
public static void main(String[] args) {
SpringApplication.run(Chapter75Application.class, args);
}
}
此時可以反復執行單元測驗,您可能會遇到各種不同的結果,比如:
-
沒有任何任務相關的輸出
-
有部分任務相關的輸出
-
亂序的任務相關的輸出
-
原因是目前
doTaskOne、doTaskTwo、doTaskThree三個函式的時候已經是異步執行了,主程式在異步呼叫之后,主程式并不會理會這三個函式是否執行完成了,由于沒有其他需要執行的內容,所以程式就自動結束了,導致了不完整或是沒有輸出任務相關內容的情況,
注:@Async所修飾的函式不要定義為static型別,這樣異步呼叫不會生效
異步回呼
為了讓doTaskOne、doTaskTwo、doTaskThree能正常結束,假設我們需要統計一下三個任務并發執行共耗時多少,這就需要等到上述三個函式都完成調動之后記錄時間,并計算結果,
那么我們如何判斷上述三個異步呼叫是否已經執行完成呢?我們需要使用CompletableFuture<T>來回傳異步呼叫的結果,就像如下方式改造doTaskOne函式:
@Async
public CompletableFuture<String> doTaskOne() throws Exception {
log.info("開始做任務一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任務一,耗時:" + (end - start) + "毫秒");
return CompletableFuture.completedFuture("任務一完成");
}
按照如上方式改造一下其他兩個異步函式之后,下面我們改造一下測驗用例,讓測驗在等待完成三個異步呼叫之后來做一些其他事情,
@Test
public void test() throws Exception {
long start = System.currentTimeMillis();
CompletableFuture<String> task1 = asyncTasks.doTaskOne();
CompletableFuture<String> task2 = asyncTasks.doTaskTwo();
CompletableFuture<String> task3 = asyncTasks.doTaskThree();
CompletableFuture.allOf(task1, task2, task3).join();
long end = System.currentTimeMillis();
log.info("任務全部完成,總耗時:" + (end - start) + "毫秒");
}
看看我們做了哪些改變:
- 在測驗用例一開始記錄開始時間
- 在呼叫三個異步函式的時候,回傳
CompletableFuture<String>型別的結果物件 - 通過
CompletableFuture.allOf(task1, task2, task3).join()實作三個異步任務都結束之前的阻塞效果 - 三個任務都完成之后,根據結束時間 - 開始時間,計算出三個任務并發執行的總耗時,
執行一下上述的單元測驗,可以看到如下結果:
2021-09-11 23:33:38.842 INFO 95891 --- [ task-3] com.didispace.chapter75.AsyncTasks : 開始做任務三
2021-09-11 23:33:38.842 INFO 95891 --- [ task-2] com.didispace.chapter75.AsyncTasks : 開始做任務二
2021-09-11 23:33:38.842 INFO 95891 --- [ task-1] com.didispace.chapter75.AsyncTasks : 開始做任務一
2021-09-11 23:33:45.155 INFO 95891 --- [ task-2] com.didispace.chapter75.AsyncTasks : 完成任務二,耗時:6312毫秒
2021-09-11 23:33:47.308 INFO 95891 --- [ task-3] com.didispace.chapter75.AsyncTasks : 完成任務三,耗時:8465毫秒
2021-09-11 23:33:47.403 INFO 95891 --- [ task-1] com.didispace.chapter75.AsyncTasks : 完成任務一,耗時:8560毫秒
2021-09-11 23:33:47.404 INFO 95891 --- [ main] c.d.chapter75.Chapter75ApplicationTests : 任務全部完成,總耗時:8590毫秒
可以看到,通過異步呼叫,讓任務一、二、三并發執行,有效的減少了程式的總運行時間,本系列教程《Spring Boot 2.x基礎教程》點擊直達!,歡迎收藏與轉發!如果學習程序中如遇困難?可以加入我們的 Spring技術交流群,參與交流與討論,更好的學習與進步!
代碼示例
本文的完整工程可以查看下面倉庫中2.x目錄下的chapter7-5工程:
- Github:https://github.com/dyc87112/SpringBoot-Learning/
- Gitee:https://gitee.com/didispace/SpringBoot-Learning/
如果您覺得本文不錯,歡迎Star支持,您的關注是我堅持的動力!
歡迎關注我的公眾號:程式猿DD,分享外面看不到的干貨與思考!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/300115.html
標籤:其他
