溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot中怎么異步調用@Async

發(fā)布時間:2021-06-24 17:04:04 來源:億速云 閱讀:335 作者:Leah 欄目:編程語言

這期內容當中小編將會給大家?guī)碛嘘PSpringBoot中怎么異步調用@Async,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

一、@Async使用演示

@Async是Spring內置注解,用來處理異步任務,在SpringBoot中同樣適用,且在SpringBoot項目中,除了boot本身的starter外,不需要額外引入依賴。

而要使用@Async,需要在啟動類上加上@EnableAsync主動聲明來開啟異步方法。

@EnableAsync@SpringBootApplicationpublic class SpringbootApplication {  public static void main(String[] args) {    SpringApplication.run(SpringbootApplication.class, args);  }}

現(xiàn)假設有3個任務需要去處理,分別對應AsyncTask類的taskOne、taskTwo、taskThree方法,這里做了線程的sleep來模擬實際運行。

@Slf4j@Componentpublic 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("任務一執(zhí)行完成耗時{}秒", (end - start)/1000f);  }    public void taskTwo() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務二執(zhí)行完成耗時{}秒", (end - start)/1000f);  }    public void taskThree() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務三執(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();    }  }}

運行測試方法,可以在控制臺看到任務一二三按順序執(zhí)行,最后主程序完成,這和我們的預期一樣,因為我們沒有任何額外的處理,他們就是普通的方法,按編碼順序依次執(zhí)行。

而如果要使任務并發(fā)執(zhí)行,我們只需要在任務方法上使用@Async注解即可,需要注意的是@Async所修飾的方法不要定義為static類型,這樣異步調用不會生效。

@Slf4j@Componentpublic class AsyncTask {  private Random random = new Random();  //@Async所修飾的函數(shù)不要定義為static類型,這樣異步調用不會生效  @Async  public void taskOne() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務一執(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("任務二執(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("任務三執(zhí)行完成耗時{}秒", (end - start)/1000f);  }}

然后我們在運行測試類,這個時候輸出可能就五花八門了,任意任務都可能先執(zhí)行完成,也有可能有的方法因為主程序關閉而沒有輸出。

二、Future獲取異步執(zhí)行結果

上面演示了@Async,但是有時候除了需要任務并發(fā)調度外,我們還需要獲取任務的返回值,且在多任務都執(zhí)行完成后再結束主任務,這個時候又該怎么處理呢?

在多線程里通過Callable和Future可以獲取返回值,這里也是類似的,我們使用Future返回方法的執(zhí)行結果,AsyncResult是Future的一個實現(xiàn)類。

@Slf4j@Componentpublic class FutureTask {  private Random random = new Random();  //@Async所修飾的函數(shù)不要定義為static類型,這樣異步調用不會生效  @Async  public Future<String> taskOne() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務一執(zhí)行完成耗時{}秒", (end - start)/1000f);    return new AsyncResult <>("任務一Ok");  }  @Async  public Future<String> taskTwo() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務二執(zhí)行完成耗時{}秒", (end - start)/1000f);    return new AsyncResult <>("任務二OK");  }  @Async  public Future<String> taskThree() throws InterruptedException {    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    log.info("任務三執(zhí)行完成耗時{}秒", (end - start)/1000f);    return new AsyncResult <>("任務三Ok");  }}

在AsyncResult中:

isDone()方法可以用于判斷異步方法是否執(zhí)行完成,若任務完成,則返回true  get()方法可用于獲取任務執(zhí)行后返回的結果  cancel(boolean mayInterruptIfRunning)可用于取消任務,參數(shù)mayInterruptIfRunning表示是否允許取消正在執(zhí)行卻沒有執(zhí)行完畢的任務,如果設置true,則表示可以取消正在執(zhí)行過程中的任務  isCancelled()方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true  get(long timeout, TimeUnit unit)用來獲取執(zhí)行結果,如果在指定時間內,還沒獲取到結果,就直接返回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個任務執(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();    }  }}

運行測試類,我們可以看到任務一二三異步執(zhí)行了,主任務最后執(zhí)行完成,而且可以獲取到任務的返回信息。

上述就是小編為大家分享的SpringBoot中怎么異步調用@Async了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI