此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 spring-cloud-task 3.2.0! |
开始
如果您刚刚开始使用 Spring Cloud Task,则应阅读本节。 在这里,我们回答了基本的 “what?”、“how?” 和 “why?” 问题。我们从 Spring Cloud Task 的简要介绍。然后,我们构建一个 Spring Cloud Task 应用程序 边走边讨论一些核心原则。
开发您的第一个 Spring Cloud 任务应用程序
一个好的起点是一个简单的 “Hello, World!” 应用程序,因此我们创建 Spring Cloud Task 等效于突出框架的功能。大多数 IDE 都有 对 Apache Maven 的良好支持,因此我们将其用作此项目的构建工具。
spring.io 网站包含许多“Getting Started ”
指南使用 Spring Boot 的 Boot。如果您需要解决特定问题,请先检查那里。
您可以通过转到 Spring Initializr 并创建一个新项目来简化以下步骤。这样做
自动生成新的项目结构,以便您可以立即开始编码。
我们建议尝试使用 Spring Initializr 来熟悉它。 |
使用 Spring Initializr 创建 Spring 任务项目
现在,我们可以创建并测试一个打印Hello, World!
拖动到控制台。
为此,请执行以下作:
-
访问 Spring Initialzr 网站。
-
创建一个 Group name 为
io.spring.demo
和 Artifact 名称helloworld
. -
在 Dependencies (依赖项) 文本框中,键入
task
,然后选择Task
依赖项替换为Spring Cloud
标签。 -
在 Dependencies (依赖项) 文本框中,键入
h2
,然后选择H2
依赖项替换为SQL
标签。 -
单击 Generate Project 按钮
-
-
解压缩 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!");
}
}
}
While it may seem small, quite a bit is going on. For more about Spring
Boot specifics, see the
Spring Boot reference documentation.
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 to DEBUG
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
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.
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.
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
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 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.
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 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:
$ 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 the TaskRepository
.
-
The execution of our ApplicationRunner
, demonstrated by the “Hello, World!” output.
-
SimpleTaskRepository
logs the completion of the task in the TaskRepository
.
A simple task application can be found in the samples module of the Spring Cloud
Task Project
here.