入门

如果您刚开始接触 Spring Cloud Task,应该阅读本节。在这里,我们将回答基本的“是什么?”、“如何做?”和“为什么?”问题。我们将从对 Spring Cloud Task 的温和介绍开始。然后,我们将构建一个 Spring Cloud Task 应用,同时讨论一些核心原则。

介绍 Spring Cloud Task

Spring Cloud Task 使创建短生命周期的微服务变得容易。它提供了能够在生产环境中按需执行短生命周期 JVM 进程的功能。

系统要求

您需要安装 Java (Java 17 或更高版本)。

数据库要求

Spring Cloud Task 使用关系型数据库存储执行任务的结果。虽然您可以在没有数据库的情况下开始开发任务(任务状态会作为任务仓库更新的一部分进行日志记录),但在生产环境中,您需要使用受支持的数据库。Spring Cloud Task 当前支持以下数据库

  • DB2

  • H2

  • HSQLDB

  • MySql

  • Oracle

  • Postgres

  • SqlServer

开发您的第一个 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! 打印到控制台的应用。

为此

  1. 访问 Spring Initializr 网站。

    1. 创建一个新的 Maven 项目,Group 名称为 io.spring.demoArtifact 名称为 helloworld

    2. 在 Dependencies 文本框中,输入 task,然后选择带有 Spring Cloud 标签的 Task 依赖。

    3. 在 Dependencies 文本框中,输入 h2,然后选择带有 SQL 标签的 H2 依赖。

    4. 点击 Generate Project 按钮

  2. 解压 helloworld.zip 文件并将项目导入您喜欢的 IDE。

编写代码

为了完成我们的应用,我们需要使用以下内容更新生成的 HelloworldApplication,以便它能够启动一个 Task。

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 数据库对于生产环境来说不是一个实用的解决方案。然而,对于快速入门体验,我们可以在示例中使用它,并将仓库中更新的内容回显到日志中。在本文档后面的配置部分,我们将介绍如何自定义 Spring Cloud Task 提供的组件配置。

当我们的示例应用运行时,Spring Boot 会启动我们的 HelloWorldApplicationRunner 并将“Hello, World!” 消息输出到标准输出。TaskLifecycleListener 会在仓库中记录任务的开始和结束。

main 方法

main 方法是任何 Java 应用的入口点。我们的 main 方法委托给 Spring Boot 的 SpringApplication 类。

ApplicationRunner

Spring 包含许多启动应用逻辑的方法。Spring Boot 通过其 *Runner 接口 (CommandLineRunnerApplicationRunner) 提供了一种有序且便捷的方式。一个良好的任务可以通过使用这两个 runner 之一来启动任何逻辑。

任务的生命周期从 *Runner#run 方法执行之前开始,到所有方法执行完成为止。Spring Boot 允许一个应用使用多个 *Runner 实现,Spring Cloud Task 也是如此。

通过 CommandLineRunnerApplicationRunner 之外的机制(例如使用 InitializingBean#afterPropertiesSet)启动的任何处理都不会被 Spring Cloud Task 记录。

运行示例

至此,我们的应用应该可以工作了。由于此应用基于 Spring Boot,我们可以从应用的根目录使用命令行 $ ./mvnw spring-boot:run 运行它,如下例所示(包含其输出)

$ mvn clean spring-boot:run
....... . . .
....... . . . (Maven log output here)
....... . . .

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.1)

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!” 输出证明。

  • SimpleTaskRepositoryTaskRepository 中记录了任务的完成。

一个简单的任务应用可以在 Spring Cloud Task 项目的 samples 模块中找到,请点击这里