Getting started
如果您刚刚开始使用 Spring Cloud Task,您应该阅读本部分。在这里,我们将回答基本“what?
”(“什么?
”)、“how?
”(“如何?
”)、“why?
”(“为什么?
”)问题。我们将以一个 Spring Cloud Task 的温和介绍作为开场白。然后,我们构建一个 Spring Cloud Task 应用程序,在构建过程中讨论一些核心原则。
If you are just getting started with Spring Cloud Task, you should read this section. Here, we answer the basic “what?”, “how?”, and “why?” questions. We start with a gentle introduction to Spring Cloud Task. We then build a Spring Cloud Task application, discussing some core principles as we go.
Introducing Spring Cloud Task
Spring Cloud Task 使创建短期微服务变得容易。它提供了可让短期 JVM 进程在生产环境中按需执行的功能。
Spring Cloud Task makes it easy to create short-lived microservices. It provides capabilities that let short-lived JVM processes be executed on demand in a production environment.
System Requirements
您需要安装 Java(Java 17 或更高版本)。
You need to have Java installed (Java 17 or better).
Database Requirements
Spring Cloud Task 使用关系数据库存储已执行任务的结果。虽然您可以在没有数据库的情况下开始开发任务(任务的状态会记录为任务存储库更新的一部分),但对于生产环境,您希望使用受支持的数据库。Spring Cloud Task 当前支持以下数据库:
Spring Cloud Task uses a relational database to store the results of an executed task. While you can begin developing a task without a database (the status of the task is logged as part of the task repository’s updates), for production environments, you want to use a supported database. Spring Cloud Task currently supports the following databases:
-
DB2
-
H2
-
HSQLDB
-
MySql
-
Oracle
-
Postgres
-
SqlServer
Developing Your First Spring Cloud Task Application
一个好的起点是使用一个简单的“Hello, World!
”应用程序,因此我们创建 Spring Cloud Task 等价项来突出该框架的功能。大多数 IDE 都很好地支持 Apache Maven,因此我们将其用作此项目的构建工具。
A good place to start is with a simple “Hello, World!” application, so we create the Spring Cloud Task equivalent to highlight the features of the framework. Most IDEs have good support for Apache Maven, so we use it as the build tool for this project.
spring.io 网站包含许多使用 Spring Boot 的 “ |
The spring.io web site contains many “ |
Creating the Spring Task Project using Spring Initializr
现在,我们可以创建一个应用程序并对其进行测试,该应用程序会将“Hello, World!
”打印到控制台。
Now we can create and test an application that prints Hello, World!
to the console.
为此,请:
To do so:
-
Visit the Spring Initialzr site.[style="loweralpha"]
-
Create a new Maven project with a Group name of
io.spring.demo
and an Artifact name ofhelloworld
. -
In the Dependencies text box, type
task
and then select theTask
dependency with theSpring Cloud
label. -
In the Dependencies text box, type
h2
and then select theH2
dependency with theSQL
label. -
Click the Generate Project button
-
-
Unzip the helloworld.zip file and import the project into your favorite IDE.
Writing the Code
要完成我们的应用程序,我们需要使用以下内容更新生成的 HelloworldApplication
,以便它启动一个任务。
To finish our application, we need to update the generated HelloworldApplication
with the following contents so that it launches a Task.
package io.spring.demo.helloworld;
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 reference documentation 。
While it may seem small, quite a bit is going on. For more about Spring Boot specifics, see the Spring Boot reference documentation.
现在,我们可以在 src/main/resources
中打开 application.properties
文件。我们需要在 application.properties
中配置两个属性:
Now we can open the application.properties
file in src/main/resources
.
We need to configure two properties in application.properties
:
-
application.name
: To set the application name (which is translated to the task name) -
logging.level
: To set the logging for Spring Cloud Task toDEBUG
in order to get a view of what is going on.
以下示例展示了如何同时执行这两项操作:
The following example shows how to do both:
logging.level.org.springframework.cloud.task=DEBUG
spring.application.name=helloWorld
Task Auto Configuration
在包含 Spring Cloud Task Starter 依赖项时,任务会自动配置所有 bean 以引导其功能。此配置的部分内容会注册 TaskRepository
及其使用的基础设施。
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.
在我们的演示中,TaskRepository
使用嵌入式 H2 数据库来记录任务的结果。此 H2 嵌入式数据库不是生产环境的实用解决方案,因为在任务结束后 H2 数据库就消失了。然而,为了快速入门,我们可以将此数据库用在我们的示例中,以及将正在更新的信息传递给日志。在 Configuration 小节(在本文档的后面部分),我们将介绍如何自定义 Spring Cloud 任务提供的组件配置。
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 Boot 会启动 HelloWorldApplicationRunner
并将“Hello, World!
” 输出到标准输出。TaskLifecycleListener
在仓库中记录任务的开始和结束。
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.
The main method
主方法充当任何 Java 应用程序的入口点。我们的主方法委派给 Spring Boot 的 SpringApplication 类。
The main method serves as the entry point to any java application. Our main method delegates to Spring Boot’s SpringApplication class.
The ApplicationRunner
Spring 提供很多方法来引导应用程序逻辑。Spring Boot 通过其 *Runner
接口(CommandLineRunner
或 ApplicationRunner
)提供了一种以有条理地执行该操作的便捷方法。一个行为良好的任务可以通过使用这两个 runner 中的一个来引导任何逻辑。
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.
任务的生命周期被认为从 *Runner#run
方法执行前到所有方法都完成后这段时间内。正如 Spring Cloud Task 所做的那样,Spring Boot 让应用程序使用多个 *Runner
实现。
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.
任何从 |
Any processing bootstrapped from mechanisms other than a |
Running the Example
此时,我们的应用程序应能正常工作。由于该应用程序基于 Spring Boot,所以我们可以使用 $ ./mvnw spring-boot:run
从应用程序的根目录运行它,如下例所示(及其输出):
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:
$ 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)
....... . . .
前面的输出有我们关注的三行:
The preceding output has three lines that are of interest to us here:
-
SimpleTaskRepository
logged the creation of the entry in theTaskRepository
. -
The execution of our
ApplicationRunner
, demonstrated by the “Hello, World!” output. -
SimpleTaskRepository
logs the completion of the task in theTaskRepository
.
可在 Spring Cloud Task 项目 here 的示例模块中找到一个简单的任务应用程序。 |
A simple task application can be found in the samples module of the Spring Cloud Task Project here. |