此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 spring-cloud-task 3.2.0spring-doc.cadn.net.cn

开始

如果您刚刚开始使用 Spring Cloud Task,则应阅读本节。 在这里,我们回答了基本的 “what?”、“how?” 和 “why?” 问题。我们从 Spring Cloud Task 的简要介绍。然后,我们构建一个 Spring Cloud Task 应用程序 边走边讨论一些核心原则。spring-doc.cadn.net.cn

Spring Cloud Task 简介

Spring Cloud Task 使创建短期微服务变得容易。它提供 允许在生产中按需执行短期 JVM 进程的功能 环境。spring-doc.cadn.net.cn

系统要求

您需要安装 Java(Java 17 或更高版本)。spring-doc.cadn.net.cn

数据库要求

Spring Cloud Task 使用关系数据库来存储已执行任务的结果。 虽然您可以在没有数据库的情况下开始开发任务(任务的状态会记录下来 作为任务存储库更新的一部分),对于生产环境,您希望 使用支持的数据库。Spring Cloud Task 目前支持以下数据库:spring-doc.cadn.net.cn

开发您的第一个 Spring Cloud 任务应用程序

一个好的起点是一个简单的 “Hello, World!” 应用程序,因此我们创建 Spring Cloud Task 等效于突出框架的功能。大多数 IDE 都有 对 Apache Maven 的良好支持,因此我们将其用作此项目的构建工具。spring-doc.cadn.net.cn

spring.io 网站包含许多Getting Started” 指南使用 Spring Boot 的 Boot。如果您需要解决特定问题,请先检查那里。 您可以通过转到 Spring Initializr 并创建一个新项目来简化以下步骤。这样做 自动生成新的项目结构,以便您可以立即开始编码。 我们建议尝试使用 Spring Initializr 来熟悉它。

使用 Spring Initializr 创建 Spring 任务项目

现在,我们可以创建并测试一个打印Hello, World!拖动到控制台。spring-doc.cadn.net.cn

为此,请执行以下作:spring-doc.cadn.net.cn

  1. 访问 Spring Initialzr 网站。spring-doc.cadn.net.cn

    1. 创建一个 Group name 为io.spring.demoArtifact 名称helloworld.spring-doc.cadn.net.cn

    2. 在 Dependencies (依赖项) 文本框中,键入task,然后选择Task依赖项替换为Spring Cloud标签。spring-doc.cadn.net.cn

    3. 在 Dependencies (依赖项) 文本框中,键入h2,然后选择H2依赖项替换为SQL标签。spring-doc.cadn.net.cn

    4. 单击 Generate Project 按钮spring-doc.cadn.net.cn

  2. 解压缩 helloworld.zip 文件并将项目导入到您最喜欢的 IDE 中。spring-doc.cadn.net.cn

编写代码

要完成我们的应用程序,我们需要更新生成的HelloworldApplication替换为以下内容,以便启动 Task。spring-doc.cadn.net.cn

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!");

		}
	}
}

While it may seem small, quite a bit is going on. For more about Spring Boot specifics, see the Spring Boot reference documentation.spring-doc.cadn.net.cn

Now we can open the application.properties file in src/main/resources. We need to configure two properties in application.properties:spring-doc.cadn.net.cn

  • application.name: To set the application name (which is translated to the task name)spring-doc.cadn.net.cn

  • logging.level: To set the logging for Spring Cloud Task to DEBUG in order to get a view of what is going on.spring-doc.cadn.net.cn

The following example shows how to do both:spring-doc.cadn.net.cn

logging.level.org.springframework.cloud.task=DEBUG
spring.application.name=helloWorld

Task Auto Configuration

When including Spring Cloud Task Starter dependency, Task auto configures all beans to bootstrap it’s functionality. Part of this configuration registers the TaskRepository and the infrastructure for its use.spring-doc.cadn.net.cn

In our demo, the TaskRepository uses an embedded H2 database to record the results of a task. This H2 embedded database is not a practical solution for a production environment, since the H2 DB goes away once the task ends. However, for a quick getting-started experience, we can use this in our example as well as echoing to the logs what is being updated in that repository. In the Configuration section (later in this documentation), we cover how to customize the configuration of the pieces provided by Spring Cloud Task.spring-doc.cadn.net.cn

When our sample application runs, Spring Boot launches our HelloWorldApplicationRunner and outputs our “Hello, World!” message to standard out. The TaskLifecycleListener records the start of the task and the end of the task in the repository.spring-doc.cadn.net.cn

The main method

The main method serves as the entry point to any java application. Our main method delegates to Spring Boot’s SpringApplication class.spring-doc.cadn.net.cn

The ApplicationRunner

Spring includes many ways to bootstrap an application’s logic. Spring Boot provides a convenient method of doing so in an organized manner through its *Runner interfaces (CommandLineRunner or ApplicationRunner). A well behaved task can bootstrap any logic by using one of these two runners.spring-doc.cadn.net.cn

The lifecycle of a task is considered from before the *Runner#run methods are executed to once they are all complete. Spring Boot lets an application use multiple *Runner implementations, as does Spring Cloud Task.spring-doc.cadn.net.cn

Any processing bootstrapped from mechanisms other than a CommandLineRunner or ApplicationRunner (by using InitializingBean#afterPropertiesSet for example) is not recorded by Spring Cloud Task.

Running the Example

At this point, our application should work. Since this application is Spring Boot-based, we can run it from the command line by using $ ./mvnw spring-boot:run from the root of our application, as shown (with its output) in the following example:spring-doc.cadn.net.cn

$ 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)
....... . . .

The preceding output has three lines that are of interest to us here:spring-doc.cadn.net.cn

A simple task application can be found in the samples module of the Spring Cloud Task Project here.