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

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

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

1、@Async使用演示

@Async是Spring內置註解,用來處理異步任務,在SpringBoot中一樣適用,且在SpringBoot項目中,除了boot自己的starter外,不須要額外引入依賴。github

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

@EnableAsync
@SpringBootApplication
public class SpringbootApplication {

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

}

現假設有3個任務須要去處理,分別對應AsyncTask類的taskOne、taskTwo、taskThree方法,這裏作了線程的sleep來模擬實際運行。springboot

@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類型,這樣異步調用不會生效。dom

@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);
    }

}

而後咱們在運行測試類,這個時候輸出可能就五花八門了,任意任務均可能先執行完成,也有可能有的方法由於主程序關閉而沒有輸出。異步

2、Future獲取異步執行結果

上面演示了@Async,可是有時候除了須要任務併發調度外,咱們還須要獲取任務的返回值,且在多任務都執行完成後再結束主任務,這個時候又該怎麼處理呢?async

在多線程裏經過Callable和Future能夠獲取返回值,這裏也是相似的,咱們使用Future返回方法的執行結果,AsyncResult<T>是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

相關文章
相關標籤/搜索