1. 概述
Spring Cloud Task 的目標是為 Spring Boot 應用程序提供創建短生命週期的微服務的功能.
在 Spring Cloud Task 中,您可以靈活地動態地運行任何任務,按需分配資源並在任務完成後檢索結果。
Tasks 是 Spring Cloud Data Flow 中引入的一種新基本單元,允許用户將 Spring Boot 應用程序作為短生命週期的任務執行.
2. 開發一個簡單的任務應用程序
This section will guide you through the process of building a simple task application. We’ll cover the key steps involved in setting up your project, defining the data model, and implementing the basic functionality. This application will serve as a foundational example for more complex task management systems.
// 任務應用程序的基本結構
// 任務數據結構
const Task = {
id: null,
title: "",
description: "",
completed: false
};
// 任務列表
let tasks = [];
2.1. 添加相關依賴
首先,我們可以添加依賴管理部分,使用 <em >spring-cloud-task-dependencies:</em >。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-dependencies</artifactId>
<version>2.2.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>此依賴管理通過導入範圍管理依賴項的版本。
我們需要添加以下依賴項:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-task</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-core</artifactId>
</dependency>此處是 Maven Central 中 spring-cloud-task-core 的鏈接。
現在,要啓動我們的 Spring Boot 應用程序,我們需要添加 spring-boot-starter 以及相關的父模塊。
我們將使用 Spring Data JPA 作為 ORM 工具,因此我們需要添加該依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.1</version>
</dependency>使用 Spring Boot 構建簡單應用程序的詳細信息,包括 Spring Data JPA,請參考這裏。
我們可以檢查最新版本的 spring-boot-starter-parent 在 Maven Central 上。
2.2. <em @EnableTask</em>> 註解
為了啓動 Spring Cloud Task 的功能,我們需要添加 <em @EnableTask</em>> 註解:
@SpringBootApplication
@EnableTask
public class TaskDemo {
// ...
}
註釋引入了SimpleTaskConfiguration 類,進而註冊了TaskRepository及其基礎設施。默認情況下,使用內存映射來存儲TaskRepository的狀態。
TaskRepository的主要信息由TaskExecution類建模。該類的註標記字段包括taskName、startTime、endTime和exitMessage。 exitMessage存儲在退出時間時的可用信息。
如果退出是由應用程序中任何事件的故障引起的,完整的異常堆棧跟蹤將存儲在此處。
Spring Boot 提供了一個接口ExitCodeExceptionMapper,它將未捕獲的異常映射為退出代碼,從而允許仔細的調試。Cloud Task 將信息存儲在數據源中以供未來分析。
2.3. 配置 DataSource 用於 TaskRepository
InMemory地圖用於存儲 TaskRepository 將在任務結束時消失,並且會丟失與任務事件相關的數據。為了存儲到永久存儲中,我們將使用 MySQL 作為數據源,並結合 Spring Data JPA。
數據源配置位於 application.yml 文件中。為了配置 Spring Cloud Task 使用提供的數據庫作為 TaskRepository 的存儲,我們需要創建一個擴展 DefaultTaskConfigurer 的類。
現在,可以將配置好的 Datasource 作為構造參數傳遞給父類構造函數:
@Autowired
private DataSource dataSource;
public class HelloWorldTaskConfigurer extends DefaultTaskConfigurer{
public HelloWorldTaskConfigurer(DataSource dataSource){
super(dataSource);
}
}為了使上述配置生效,我們需要對一個 DataSource 實例進行標註,並使用 @Autowired 註解進行注入,同時將其作為 HelloWorldTaskConfigurer bean 的構造參數:
@Bean
public HelloWorldTaskConfigurer getTaskConfigurer() {
return new HelloWorldTaskConfigurer(dataSource);
}這完成了將 TaskRepository 存儲到 MySQL 數據庫的配置。
2.4. 實現
在 Spring Boot 中,我們可以執行任何任務在應用程序完成啓動之前。我們可以使用 ApplicationRunner 或 CommandLineRunner 接口來創建簡單的任務。
我們需要實現這些接口的 run 方法,並聲明實現類為 Bean:
@Component
public static class HelloWorldApplicationRunner
implements ApplicationRunner {
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Spring Cloud Task!");
}
}現在,如果運行我們的應用程序,我們應該得到任務產生必要的輸出,並在我們的 MySQL 數據庫中創建所需的表,這些表記錄了任務的事件數據。
3. Spring Cloud 任務生命週期
首先,我們在 TaskRepository 中創建一條記錄。這表明所有 Bean 已經準備好在 Application 中使用,並且 Runner 接口中的 run 方法已準備好執行。
在執行 run 方法完成或 ApplicationContext 事件發生任何錯誤時,TaskRepository 將被更新為另一條記錄。
在任務生命週期中,我們可以註冊來自 TaskExecutionListener 接口的監聽器。我們需要一個實現該接口的類,該類具有三個方法—— onTaskEnd、 onTaksFailed 和 onTaskStartup,這些方法在任務的相應事件觸發時觸發。
我們需要在我們的 TaskDemo 類中聲明實現類的 Bean:
@Bean
public TaskListener taskListener() {
return new TaskListener();
}4. 與 Spring Batch 集成
我們可以將 Spring Batch 作業作為任務執行,並使用 Spring Cloud Task 記錄作業執行事件。為了啓用此功能,我們需要添加與 Boot 和 Cloud 相關的 Batch 依賴項。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-batch</artifactId>
</dependency>此處 是 Maven Central 中 spring-cloud-task-batch 的鏈接。
為了將任務配置為 Task,我們需要在 JobConfiguration 類中註冊 Job bean:
@Bean
public Job job2() {
return jobBuilderFactory.get("job2")
.start(stepBuilderFactory.get("job2step1")
.tasklet(new Tasklet(){
@Override
public RepeatStatus execute(
StepContribution contribution,
ChunkContext chunkContext) throws Exception {
System.out.println("This job is from Baeldung");
return RepeatStatus.FINISHED;
}
}).build()).build();
}我們需要為 TaskDemo 類添加 @EnableBatchProcessing 註解:
//..Other Annotation..
@EnableBatchProcessing
public class TaskDemo {
// ...
}@EnableBatchProcessing 註解允許啓用 Spring Batch 功能,並提供必要的配置來設置批處理作業。
現在,如果運行應用程序,@EnableBatchProcessing 註解將觸發 Spring Batch Job 的執行,Spring Cloud Task 將記錄所有批處理作業執行的事件,以及在 springcloud 數據庫中執行的其他任務。
5. 從流中啓動任務
我們可以從 Spring Cloud Stream 觸發任務。為此,我們有 @EnableTaskLaucnher 註解:
@SpringBootApplication
@EnableTaskLauncher
public class SpringCloudTaskStreamBridgeApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudTaskStreamBridgeApplication.class, args);
}
}為了使我們的任務能夠正常運行,我們需要一個配置的 Bean,該 Bean 實現 TaskLauncher 接口。
@Bean
public TaskLauncher taskLauncher() {
return mock(TaskLauncher.class);
}需要注意的是,TaskLauncher spring-cloud-deployer-local 依賴項必須已添加後,TaskLauncher 接口才可用。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-deployer-local</artifactId>
<version>2.9.3</version>
</dependency>我們可以通過調用 StreamBridge 接口中的 send() 方法來測試任務是否啓動:
public class SpringCloudTaskStreamBridgeIntegrationTest {
@Autowired
private StreamBridge streamBridge;
//
}現在,我們創建一個 TaskLaunchRequest 實例,並將該實例作為 GenericMessage<TaskLaunchRequest> 對象的 payload 發送。然後,我們可以調用 StreamBridge 的 send() 方法,同時將 GenericMessage 對象保留在通道中。
6. 結論
在本教程中,我們探討了 Spring Cloud Task 的執行方式以及如何將其配置為在數據庫中記錄事件。我們還觀察了 Spring Batch 任務的定義和存儲在 TaskRepository 中。最後,我們解釋瞭如何從 Spring Cloud Stream 中觸發任務。