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
@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-as