這篇文章主要介紹了springboot異步調用是什么,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
同步
程序按照定義順序依次執行,每一行程序都必須等待上一行程序執行完成之后才能執行,就是在發出一個功能調用時,在沒有得到結果之前,該調用就不返回。
異步
程序在順序執行時,不等待異步調用的語句返回結果就執行后面的程序,當一個異步過程調用發出后,調用者不能立刻得到結果。
同步代碼
Service層:
public void test() throws InterruptedException { Thread.sleep(2000); for (int i = 0; i < 1000; i++) { System.out.println("i = " + i); } }
Controller層:
@GetMapping("test") public String test() { try { Thread.sleep(1000); System.out.println("主線程開始"); for (int j = 0; j < 100; j++) { System.out.println("j = " + j); } asyncService.test(); System.out.println("主線程結束"); return "async"; } catch (InterruptedException e) { e.printStackTrace(); return "fail"; } }
瀏覽器中請求 http://localhost:8080/test
控制臺打印順序:
在Service層的test方法上加上@Async
注解,同時為了是異步生效在啟動類上加上@EnableAsync
注解
Service層:
@Async public void test() throws InterruptedException { Thread.sleep(2000); for (int i = 0; i < 1000; i++) { System.out.println("i = " + i); } }
Controller不變,啟動類加上@EnableAsync
:
@SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } }
再次請求打印順序如下:
感謝你能夠認真閱讀完這篇文章,希望小編分享springboot異步調用是什么內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。