SpringBoot系列:Spring Boot異步調用@Async


在實際開發中,有時候為了及時處理請求和進行響應,我們可能會多任務同時執行,或者先處理主任務,也就是異步調用,異步調用的實現有很多,例如多線程、定時任務、消息隊列等,

這一章節,我們就來講講@Async異步方法調用。

一、@Async使用演示

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

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

@EnableAsync
@SpringBootApplication
public class SpringbootApplication {

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

}

現假設有3個任務需要去處理,分別對應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("任務一執行完成耗時{}秒", (end - start)/1000f);
    }
    
    public void taskTwo() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任務二執行完成耗時{}秒", (end - start)/1000f);
    }
    
    public void taskThree() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任務三執行完成耗時{}秒", (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("主程序執行完成耗時{}秒", (end - start)/1000f);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

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

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

@Slf4j
@Component
public class AsyncTask {

    private Random random = new Random();

    //@Async所修飾的函數不要定義為static類型,這樣異步調用不會生效
    @Async
    public void taskOne() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任務一執行完成耗時{}秒", (end - start)/1000f);
    }

    @Async
    public void taskTwo() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任務二執行完成耗時{}秒", (end - start)/1000f);
    }

    @Async
    public void taskThree() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任務三執行完成耗時{}秒", (end - start)/1000f);
    }

}

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

二、Future獲取異步執行結果

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

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

@Slf4j
@Component
public class FutureTask {

    private Random random = new Random();

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

}

在AsyncResult中:

  • isDone()方法可以用於判斷異步方法是否執行完成,若任務完成,則返回true
  • get()方法可用於獲取任務執行后返回的結果
  • cancel(boolean mayInterruptIfRunning)可用於取消任務,參數mayInterruptIfRunning表示是否允許取消正在執行卻沒有執行完畢的任務,如果設置true,則表示可以取消正在執行過程中的任務
  • isCancelled()方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true
  • get(long timeout, TimeUnit unit)用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回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個任務執行完成之后再執行主程序
            do {
                Thread.sleep(100);
            } while (future1.isDone() && future2.isDone() && future3.isDone());
            log.info("獲取異步方法的返回值:{}", future1.get());
            Thread.sleep(5000);
            long end = System.currentTimeMillis();
            log.info("主程序執行完成耗時{}秒", (end - start)/1000f);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

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

源碼地址:https://github.com/imyanger/springboot-project/tree/master/p23-springboot-async


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM