入門

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 Web サイトには、Spring Boot を使用する "Getting Started" ガイドが多数含まれています。特定の問題を解決する必要がある場合は、まずそこを確認してください。Spring Initializr に移動して新しいプロジェクトを作成すると、次の手順を短縮できます。これにより、新しいプロジェクト構造が自動的に生成されるため、すぐにコーディングを開始できます。Spring Initializr に慣れるために、試してみることをお勧めします。

Spring Initializr を使用した Spring タスクプロジェクトの作成

これで、Hello, World! をコンソールに出力するアプリケーションを作成してテストできるようになりました。

そうするために:

  1. Spring イニシャル zr サイトにアクセスしてください。

    1. グループ名が io.spring.demo成果物名が helloworld の新しい Maven プロジェクトを作成します。

    2. 依存関係 テキストボックスに " task " と入力し、Spring Cloud ラベルが付いた Task 依存関係を選択します。

    3. 依存関係 テキストボックスに " h2 " と入力し、SQL ラベルが付いた H2 依存関係を選択します。

    4. "プロジェクトを生成する " ボタンをクリックします

  2. helloworld.zip ファイルを解凍し、プロジェクトをお気に入りの IDE にインポートします。

コードの作成

アプリケーションを完成するには、タスクを起動できるように、生成された HelloworldApplication を次の内容で更新する必要があります。

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 で 2 つのプロパティを設定する必要があります。

  • application.name: アプリケーション名を設定するには (これはタスク名に変換されます)

  • logging.level: 何が起こっているかを把握するために、Spring Cloud Task のログを DEBUG に設定します。

次の例は、両方を行う方法を示しています。

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

タスクの自動構成

Spring Cloud Task Starter 依存関係を含めると、タスクはすべての Bean がその機能をブートストラップするように自動構成します。この構成の一部では、TaskRepository とその使用のためのインフラストラクチャを登録します。

デモでは、TaskRepository は組み込みの H2 データベースを使用してタスクの結果を記録します。H2 DB はタスクが終了すると消滅するため、この H2 組み込みデータベースは運用環境にとって実用的なソリューションではありません。ただし、簡単に開始するために、この例でこれを使用するだけでなく、そのリポジトリで更新されている内容をログにエコーすることもできます。構成セクション (このドキュメントの後半) では、Spring Cloud Task によって提供される要素の構成をカスタマイズする方法について説明します。

サンプルアプリケーションが実行されると、Spring Boot は HelloWorldApplicationRunner を起動し、"Hello, World!" を出力します。標準出力へのメッセージ。TaskLifecycleListener は、タスクの開始と終了をリポジトリに記録します。

主なメソッド

main メソッドは、java アプリケーションへのエントリポイントとして機能します。私たちのメインメソッドは Spring Boot の SpringApplication クラスにデリゲートします。

ApplicationRunner

Spring には、アプリケーションのロジックをブートストラップするための多くの方法が含まれています。Spring Boot は、*Runner インターフェース (CommandLineRunner または ApplicationRunner) を通じて、組織的な方法でこれを行うための便利な方法を提供します。適切に動作するタスクは、これら 2 つのランナーのいずれかを使用して任意のロジックをブートストラップできます。

タスクのライフサイクルは、*Runner#run メソッドが実行される前から、すべてのメソッドが完了するまで考慮されます。Spring Boot では、Spring Cloud Task と同様に、アプリケーションで複数の *Runner 実装を使用できます。

CommandLineRunner または ApplicationRunner 以外のメカニズムから (たとえば 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)
....... . . .

前述の出力には、ここで興味深い 3 行があります。

  • SimpleTaskRepository は、エントリの作成を TaskRepository に記録しました。

  • "Hello, World!" によって示される ApplicationRunner の実行。出力。

  • SimpleTaskRepository はタスクの補完を TaskRepository に記録します。

簡単なタスクアプリケーションは、ここの Spring Cloud Task プロジェクトのサンプルモジュールにあります。