詳細講解springboot如何實現(xiàn)異步任務
Spring Boot介紹
Spring Boot 是由 Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring 應用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進行配置,從而使開發(fā)人員不再需要定義樣板化的配置。用我的話來理解,就是 Spring Boot 其實不是什么新的框架,它默認配置了很多框架的使用方式,就像 Maven 整合了所有的 Jar 包,Spring Boot 整合了所有的框架。
Spring Boot特點
1)創(chuàng)建獨立的Spring應用程序;
2)直接嵌入Tomcat,Jetty或Undertow,無需部署WAR文件;
3)提供推薦的基礎POM文件(starter)來簡化Apache Maven配置;
4)盡可能的根據(jù)項目依賴來自動配置Spring框架;
5)提供可以直接在生產(chǎn)環(huán)境中使用的功能,如性能指標,應用信息和應用健康檢查;
6)開箱即用,沒有代碼生成,不需要配置過多的xml。同時也可以修改默認值來滿足特定的需求。
7)其他大量的項目都是基于Spring Boot之上的,如Spring Cloud。
異步任務
實例:
在service中寫一個hello方法,讓它延遲三秒
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("數(shù)據(jù)正在處理!");
}
}
讓Controller去調(diào)用這個業(yè)務
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
啟動SpringBoot項目,我們會發(fā)現(xiàn)三秒后才會響應ok。
所以我們要用異步任務去解決這個問題,很簡單就是加一個注解。
在hello方法上@Async注解
@Service
public class AsyncService {
//異步任務
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("數(shù)據(jù)正在處理!");
}
}
在SpringBoot啟動類上開啟異步注解的功能
@SpringBootApplication
//開啟了異步注解的功能
@EnableAsync
public class Sprintboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Sprintboot09TestApplication.class, args);
}
}
問題解決,服務端瞬間就會響應給前端數(shù)據(jù)!
樹越是向往高處的光亮,它的根就越要向下,向泥土向黑暗的深處。
到此這篇關于詳細講解springboot如何實現(xiàn)異步任務的文章就介紹到這了,更多相關springboot 異步任務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解析SpringSecurity自定義登錄驗證成功與失敗的結(jié)果處理問題
這篇文章主要介紹了SpringSecurity系列之自定義登錄驗證成功與失敗的結(jié)果處理問題,本文通過實例給大家講解的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
Java BufferWriter寫文件寫不進去或缺失數(shù)據(jù)的解決
這篇文章主要介紹了Java BufferWriter寫文件寫不進去或缺失數(shù)據(jù)的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
解決Beanutils.copyproperties實體類對象不一致的問題
這篇文章主要介紹了解決Beanutils.copyproperties實體類對象不一致的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

