開始
如果您剛開始使用 Spring Cloud Task,您應該閱讀本節。在這裡,我們將回答基本的“是什麼?”、“如何做?”和“為什麼?”等問題。我們首先對 Spring Cloud Task 進行簡單介紹。然後,我們構建一個 Spring Cloud Task 應用程式,並在過程中討論一些核心原則。
開發您的第一個 Spring Cloud Task 應用程式
一個好的起點是一個簡單的“Hello, World!”應用程式,因此我們建立 Spring Cloud Task 等效應用程式以突出框架的功能。大多數 IDE 對 Apache Maven 都有很好的支援,因此我們將其用作此專案的構建工具。
spring.io 網站包含許多使用 Spring Boot 的“入門”指南。如果您需要解決特定問題,請先在那裡檢視。您可以透過訪問 Spring Initializr 並建立一個新專案來簡化以下步驟。這樣做會自動生成新的專案結構,以便您可以立即開始編寫程式碼。我們建議嘗試使用 Spring Initializr 來熟悉它。 |
使用 Spring Initializr 建立 Spring Task 專案
現在我們可以建立並測試一個在控制檯列印 Hello, World! 的應用程式。
為此:
-
訪問 Spring Initializr 網站。
-
建立一個新的 Maven 專案,Group 名稱為
io.spring.demo,Artifact 名稱為helloworld。 -
在 Dependencies 文字框中,輸入
task,然後選擇帶有Spring Cloud標籤的Task依賴項。 -
在 Dependencies 文字框中,輸入
h2,然後選擇帶有SQL標籤的H2依賴項。 -
點選 Generate Project 按鈕
-
-
解壓 helloworld.zip 檔案,並將專案匯入您喜歡的 IDE。
編寫程式碼
為了完成我們的應用程式,我們需要用以下內容更新生成的 HelloworldApplication,以便它啟動一個任務。
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableTask
public class HelloworldApplication {
@Bean
public ApplicationRunner applicationRunner() {
return new HelloWorldApplicationRunner();
}
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
public static class HelloWorldApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Hello, World!");
}
}
}
雖然看起來很小,但其中包含了許多內容。有關 Spring Boot 的具體細節,請參閱 Spring Boot 參考文件。
現在我們可以開啟 src/main/resources 中的 application.properties 檔案。我們需要在 application.properties 中配置兩個屬性:
-
application.name:設定應用程式名稱(它被轉換為任務名稱) -
logging.level:將 Spring Cloud Task 的日誌記錄設定為DEBUG,以便檢視正在發生的事情。
以下示例展示瞭如何同時執行這兩項操作
logging.level.org.springframework.cloud.task=DEBUG
spring.application.name=helloWorld
任務自動配置
當包含 Spring Cloud Task Starter 依賴項時,Task 會自動配置所有 bean 以啟動其功能。此配置的一部分註冊了 TaskRepository 及其基礎設施。
在我們的演示中,TaskRepository 使用嵌入式 H2 資料庫來記錄任務的結果。這個 H2 嵌入式資料庫對於生產環境來說不是一個實用的解決方案,因為任務結束後 H2 DB 就會消失。然而,對於快速入門體驗,我們可以在示例中使用它,並將其更新到日誌中,以顯示該倉庫中正在更新的內容。在配置部分(本文件稍後),我們將介紹如何自定義 Spring Cloud Task 提供的元件的配置。
當我們的示例應用程式執行時,Spring Boot 會啟動我們的 HelloWorldApplicationRunner 並將“Hello, World!”訊息輸出到標準輸出。TaskLifecycleListener 在儲存庫中記錄任務的開始和結束。
主方法
main 方法作為任何 Java 應用程式的入口點。我們的 main 方法委託給 Spring Boot 的 SpringApplication 類。
ApplicationRunner
Spring 包含多種引導應用程式邏輯的方法。Spring Boot 透過其 *Runner 介面(CommandLineRunner 或 ApplicationRunner)提供了一種方便且有組織的方法。一個行為良好的任務可以透過使用這些執行器中的一個來引導任何邏輯。
任務的生命週期被認為是:在 *Runner#run 方法執行之前開始,直到所有方法都完成。Spring Boot 允許應用程式使用多個 *Runner 實現,Spring Cloud Task 也是如此。
透過 CommandLineRunner 或 ApplicationRunner 以外的機制(例如,使用 InitializingBean#afterPropertiesSet)引導的任何處理都不會被 Spring Cloud Task 記錄。 |
執行示例
至此,我們的應用程式應該可以工作了。由於此應用程式是基於 Spring Boot 的,我們可以從應用程式根目錄使用 $ ./mvnw spring-boot:run 從命令列執行它,如以下示例所示(及其輸出):
$ mvn clean spring-boot:run
....... . . .
....... . . . (Maven log output here)
....... . . .
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.3.0)
2024-01-04T10:07:01.102-06:00 INFO 18248 --- [helloWorld] [ main] i.s.d.helloworld.HelloworldApplication : Starting HelloworldApplication using Java 21.0.1 with PID 18248 (/Users/dashaun/fun/dashaun/spring-cloud-task/helloworld/target/classes started by dashaun in /Users/dashaun/fun/dashaun/spring-cloud-task/helloworld)
2024-01-04T10:07:01.103-06:00 INFO 18248 --- [helloWorld] [ main] i.s.d.helloworld.HelloworldApplication : No active profile set, falling back to 1 default profile: "default"
2024-01-04T10:07:01.526-06:00 INFO 18248 --- [helloWorld] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2024-01-04T10:07:01.626-06:00 INFO 18248 --- [helloWorld] [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:3ad913f8-59ce-4785-bf8e-d6335dff6856 user=SA
2024-01-04T10:07:01.627-06:00 INFO 18248 --- [helloWorld] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2024-01-04T10:07:01.633-06:00 DEBUG 18248 --- [helloWorld] [ main] o.s.c.t.c.SimpleTaskAutoConfiguration : Using org.springframework.cloud.task.configuration.DefaultTaskConfigurer TaskConfigurer
2024-01-04T10:07:01.633-06:00 DEBUG 18248 --- [helloWorld] [ main] o.s.c.t.c.DefaultTaskConfigurer : No EntityManager was found, using DataSourceTransactionManager
2024-01-04T10:07:01.639-06:00 DEBUG 18248 --- [helloWorld] [ main] o.s.c.t.r.s.TaskRepositoryInitializer : Initializing task schema for h2 database
2024-01-04T10:07:01.772-06:00 DEBUG 18248 --- [helloWorld] [ main] o.s.c.t.r.support.SimpleTaskRepository : Creating: TaskExecution{executionId=0, parentExecutionId=null, exitCode=null, taskName='helloWorld', startTime=2024-01-04T10:07:01.757268, endTime=null, exitMessage='null', externalExecutionId='null', errorMessage='null', arguments=[]}
2024-01-04T10:07:01.785-06:00 INFO 18248 --- [helloWorld] [ main] i.s.d.helloworld.HelloworldApplication : Started HelloworldApplication in 0.853 seconds (process running for 1.029)
Hello, World!
2024-01-04T10:07:01.794-06:00 DEBUG 18248 --- [helloWorld] [ main] o.s.c.t.r.support.SimpleTaskRepository : Updating: TaskExecution with executionId=1 with the following {exitCode=0, endTime=2024-01-04T10:07:01.787112, exitMessage='null', errorMessage='null'}
2024-01-04T10:07:01.799-06:00 INFO 18248 --- [helloWorld] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2024-01-04T10:07:01.806-06:00 INFO 18248 --- [helloWorld] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
....... . . .
....... . . . (Maven log output here)
....... . . .
前面的輸出中有三行是我們感興趣的:
-
SimpleTaskRepository記錄了TaskRepository中條目的建立。 -
我們的
ApplicationRunner的執行,由“Hello, World!”輸出演示。 -
SimpleTaskRepository記錄了TaskRepository中任務的完成。
| 一個簡單的任務應用程式可以在 Spring Cloud Task 專案的 samples 模組中找到這裡。 |