首頁  >  文章  >  Java  >  springboot怎麼實現非同步任務

springboot怎麼實現非同步任務

WBOY
WBOY轉載
2023-05-14 15:07:061469瀏覽

Spring Boot介紹

Spring Boot 是由 Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring 應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,使開發人員不再需要定義樣板化的配置。用我的話來理解,就是 Spring Boot 其實不是什麼新的框架,它預設配置了很多框架的使用方式,就像 Maven 整合了所有的 Jar 包,Spring Boot 整合了所有的框架。

Spring Boot特點

1)創建獨立的Spring應用程式;

#2)直接嵌入Tomcat,Jetty或Undertow,無需部署WAR檔案;

#3)提供推薦的基礎POM檔案(starter)來簡化Apache Maven配置;

4)盡可能的根據專案依賴來自動配置Spring框架;

5)提供可以直接在生產環境中使用的功能,如效能指標,應用資訊和應用健康檢查;

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("数据正在处理!");
    }
}

讓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);
    }

}

問題解決,服務端瞬間就會回應給前端資料!

樹越是嚮往高處的光亮,它的根就越要向下,向泥土向黑暗的深處。

以上是springboot怎麼實現非同步任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除