1. SpringBoot 同步執行方法
學習 SpringBoot 異步執行方法 之前我們先看一個同步執行的例子。
首先是一個 Service 類:TestAsyncService.java,這裏只是爲了演示,就沒有訪問數據庫和編寫接口。
@Service
public class TestAsyncService {
public String getResult() {
System.out.println("getResult() start...");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("getResult() end...");
return "TestAsync";
}
}
然後一個 Controller 類 :TestAsyncController , 調用 TestAsyncService 如下所示 。
@EnableAutoConfiguration
@RestController
public class TestAsyncController {
@Autowired
TestAsyncService testAsyncService;
@RequestMapping("/testAsyncController")
public String testAsyncController() {
String result;
System.out.println("testAsyncController() start...");
result = testAsyncService.getResult();
System.out.println("testAsyncController() end...");
return "結果:" + result;
}
}
重新啓動工程,訪問:http://localhost:8080/testAsyncController。
他會現有 3 秒 的卡頓,卡頓是因爲 TestAsyncService。
然後出現結果:
四條輸出語句如下所示:
2. SpringBoot 異步執行方法
SpringBoot 異步執行方法原理是創建了一個新的線程去運行 service 的方法,這會導致 controller 已經執行完成,而 service 還在運行,當然 controller 獲取不到 service 的執行結果。使用到的註解是 @Async 。
第一步:修改啓動類,需要添加@EnableAsync 這個註解開啓異步調用。
// 啓動類上加上@SpringBootApplication註解,當前包下或者子包下所有的類都可以掃到
@SpringBootApplication
// @EnableAsync 開啓異步調用
@EnableAsync
public class SpringbootStudy01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootStudy01Application.class, args);
}
}
第二步:修改 TestAsyncService 嗎,如下所示。
@Service
public class TestAsyncService {
@Async
public String getResult() {
System.out.println("getResult() start...");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("getResult() end...");
return "TestAsync";
}
}
TestAsyncController 不需修改,重新啓動工程,訪問 : http://localhost:8080/testAsyncController 。
運行截圖如下所示:
顯然,controller 已經執行完成,而 service 還在運行。