異步任務-springboot
- 異步:異步與同步相對,當一個異步程序呼叫發出后,呼叫者在沒有得到結果之前,就可以繼續執行后續操作,也就是說無論異步方法執行代碼需要多長時間,跟主執行緒沒有任何影響,主執行緒可以繼續向下執行,
實體:
在service中寫一個hello方法,讓它延遲三秒
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("資料正在處理!");
}
}
讓Controller去呼叫這個業務
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
啟動SpringBoot專案,我們會發現三秒后才會回應ok,
所以我們要用異步任務去解決這個問題,很簡單就是加一個注解,
- 在hello方法上@Async注解
@Service
public class AsyncService {
//異步任務
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("資料正在處理!");
}
}
- 在SpringBoot啟動類上開啟異步注解的功能
@SpringBootApplication
//開啟了異步注解的功能
@EnableAsync
public class Sprintboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Sprintboot09TestApplication.class, args);
}
}
問題解決,服務端瞬間就會回應給前端資料!
樹越是向往高處的光亮,它的根就越要向下,向泥土向黑暗的深處,轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457530.html
標籤:Java
上一篇:PDF加密、分割和生成封面圖操作
下一篇:Java陣列的常見演算法2
