在實(shí)際開發(fā)中俱箱,有時候?yàn)榱思皶r處理請求和進(jìn)行響應(yīng)国瓮,我們可能會多任務(wù)同時執(zhí)行,或者先處理主任務(wù)匠楚,也就是異步調(diào)用巍膘,異步調(diào)用的實(shí)現(xiàn)有很多厂财,例如多線程芋簿、定時任務(wù)、消息隊(duì)列等璃饱,
這一章節(jié)与斤,我們就來講講@Async異步方法調(diào)用。
一荚恶、@Async使用演示
@Async是Spring內(nèi)置注解撩穿,用來處理異步任務(wù),在SpringBoot中同樣適用谒撼,且在SpringBoot項(xiàng)目中食寡,除了boot本身的starter外,不需要額外引入依賴廓潜。
而要使用@Async抵皱,需要在啟動類上加上@EnableAsync主動聲明來開啟異步方法善榛。
@EnableAsync
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
現(xiàn)假設(shè)有3個任務(wù)需要去處理,分別對應(yīng)AsyncTask類的taskOne呻畸、taskTwo移盆、taskThree方法,這里做了線程的sleep來模擬實(shí)際運(yùn)行伤为。
@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("任務(wù)一執(zhí)行完成耗時{}秒", (end - start)/1000f);
}
public void taskTwo() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)二執(zhí)行完成耗時{}秒", (end - start)/1000f);
}
public void taskThree() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)三執(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();
}
}
}
運(yùn)行測試方法,可以在控制臺看到任務(wù)一二三按順序執(zhí)行位衩,最后主程序完成蚁署,這和我們的預(yù)期一樣,因?yàn)槲覀儧]有任何額外的處理蚂四,他們就是普通的方法光戈,按編碼順序依次執(zhí)行。
而如果要使任務(wù)并發(fā)執(zhí)行遂赠,我們只需要在任務(wù)方法上使用@Async注解即可久妆,需要注意的是@Async所修飾的方法不要定義為static類型,這樣異步調(diào)用不會生效跷睦。
@Slf4j
@Component
public class AsyncTask {
private Random random = new Random();
//@Async所修飾的函數(shù)不要定義為static類型筷弦,這樣異步調(diào)用不會生效
@Async
public void taskOne() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)一執(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("任務(wù)二執(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("任務(wù)三執(zhí)行完成耗時{}秒", (end - start)/1000f);
}
}
然后我們在運(yùn)行測試類,這個時候輸出可能就五花八門了抑诸,任意任務(wù)都可能先執(zhí)行完成烂琴,也有可能有的方法因?yàn)橹鞒绦蜿P(guān)閉而沒有輸出。
二蜕乡、Future獲取異步執(zhí)行結(jié)果
上面演示了@Async奸绷,但是有時候除了需要任務(wù)并發(fā)調(diào)度外,我們還需要獲取任務(wù)的返回值层玲,且在多任務(wù)都執(zhí)行完成后再結(jié)束主任務(wù)号醉,這個時候又該怎么處理呢?
在多線程里通過Callable和Future可以獲取返回值辛块,這里也是類似的畔派,我們使用Future返回方法的執(zhí)行結(jié)果,AsyncResult<T>是Future的一個實(shí)現(xiàn)類润绵。
@Slf4j
@Component
public class FutureTask {
private Random random = new Random();
//@Async所修飾的函數(shù)不要定義為static類型线椰,這樣異步調(diào)用不會生效
@Async
public Future<String> taskOne() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)一執(zhí)行完成耗時{}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)一Ok");
}
@Async
public Future<String> taskTwo() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)二執(zhí)行完成耗時{}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)二OK");
}
@Async
public Future<String> taskThree() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)三執(zhí)行完成耗時{}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)三Ok");
}
}
在AsyncResult中:
- isDone()方法可以用于判斷異步方法是否執(zhí)行完成,若任務(wù)完成尘盼,則返回true
- get()方法可用于獲取任務(wù)執(zhí)行后返回的結(jié)果
- cancel(boolean mayInterruptIfRunning)可用于取消任務(wù)憨愉,參數(shù)mayInterruptIfRunning表示是否允許取消正在執(zhí)行卻沒有執(zhí)行完畢的任務(wù)呜魄,如果設(shè)置true,則表示可以取消正在執(zhí)行過程中的任務(wù)
- isCancelled()方法表示任務(wù)是否被取消成功莱衩,如果在任務(wù)正常完成前被取消成功爵嗅,則返回 true
- get(long timeout, TimeUnit unit)用來獲取執(zhí)行結(jié)果,如果在指定時間內(nèi)笨蚁,還沒獲取到結(jié)果睹晒,就直接返回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個任務(wù)執(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();
}
}
}
運(yùn)行測試類,我們可以看到任務(wù)一二三異步執(zhí)行了括细,主任務(wù)最后執(zhí)行完成伪很,而且可以獲取到任務(wù)的返回信息。
源碼地址:https://github.com/imyanger/springboot-project/tree/master/p23-springboot-async