SmallRye Health
このガイドでは、 MicroProfile Health仕様の実装である SmallRye HealthをQuarkusアプリケーションで使用する方法を説明します。
SmallRye Healthは、アプリケーションがその状態に関する情報を外部のビューアーに提供することを可能にします。これは、典型的には自動化されたプロセスがアプリケーションを破棄すべきか再起動すべきかを判断できなければならないクラウド環境において、有用です。
前提条件
このガイドを完成させるには、以下が必要です:
-
約15分
-
IDE
-
JDK 11+ がインストールされ、
JAVA_HOME
が適切に設定されていること -
Apache Maven 3.8.1+
-
使用したい場合、 Quarkus CLI
-
ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること
アーキテクチャ
このガイドでは、仕様書に従って /q/health/live
と /q/health/ready
のエンドポイントで MicroProfile Health の機能を公開するシンプルな REST アプリケーションを構築します。
ソリューション
次のセクションで紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。
Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.git
、 アーカイブ をダウンロードします。
このソリューションは、 microprofile-health-quickstart
ディレクトリ にあります。
Mavenプロジェクトの作成
まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します。
このコマンドは、 smallrye-health
エクステンションをインポートしたプロジェクトを生成します。
すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリで以下のコマンドを実行することで、 smallrye-health
エクステンションをプロジェクトに追加することができます。
quarkus extension add 'smallrye-health'
./mvnw quarkus:add-extension -Dextensions="smallrye-health"
./gradlew addExtension --extensions="smallrye-health"
これにより、ビルドファイルに以下が追加されます:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-health</artifactId>
</dependency>
implementation("io.quarkus:quarkus-smallrye-health")
ヘルスチェックの実行
smallrye-health
エクステンションを直接インポートすると、3つのRESTエンドポイントが公開されます。
-
/q/health/live
- アプリケーションが起動していること -
/q/health/ready
- アプリケーションは、リクエストに対応する準備ができていること -
/q/health/live
- アプリケーションが起動していること -
/q/health
- アプリケーションのすべてのヘルスチェック手順の累積
smallrye-health
エクステンションが期待通りに動作しているかのチェック
-
Quarkusアプリケーションを次のように起動します:
CLIquarkus dev
Maven./mvnw quarkus:dev
Gradle./gradlew --console=plain quarkusDev
-
http://localhost:8080/q/health/live
エンドポイントにブラウザか、curl http://localhost:8080/q/health/live
でアクセス
All health
REST endpoints return a simple JSON object with two fields:
-
status
— the overall result of all the health check procedures -
checks
— an array of individual checks
ヘルスチェックの一般的な status
は、宣言されたすべてのヘルスチェックの論理的な AND として計算されます。 checks
配列は、まだヘルスチェックの手順を指定していないので空ですが、いくつか定義してみましょう。
初めてのヘルスチェックの作成
このセクションでは、最初の簡単なヘルスチェック手順を作成します。
org.acme.microprofile.health.SimpleHealthCheck
クラスを作成
package org.acme.microprofile.health;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Liveness;
import javax.enterprise.context.ApplicationScoped;
@Liveness
@ApplicationScoped (1) (2)
public class SimpleHealthCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.up("Simple health check");
}
}
1 | すべてのヘルスチェック要求に単一のBeanインスタンスが使用されるように、ヘルスチェッククラスに @ApplicationScoped または @Singleton のスコープでアノテーションを付けることをお勧めします。 |
2 | ヘルスチェックアノテーションの1つでアノテーションされたBeanクラスがスコープを宣言していない場合、 @Singleton のスコープが自動的に使用されます。 |
ご覧のように、ヘルスチェック・プロシージャは、 HealthCheck
インターフェースを実装するCDI Beanとして定義され、次のようなヘルスチェック修飾子の1つでアノテーションされています。
-
@Liveness
-/q/health/live
でアクセス可能なLivenessチェック -
@Readiness
-/q/health/ready
でアクセス可能なReadinessチェック
HealthCheck
は関数インターフェースで、その単一のメソッド call
は HealthCheckResponse
オブジェクトを返します。このオブジェクトは、例で示した fluent builder API で簡単に構築することができます。
Quarkusアプリケーションを開発モードで起動しているので、 http://localhost:8080/q/health/live
へのリクエストを ブラウザウィンドウを更新するか curl http://localhost:8080/q/health/live
で単に繰り返してください。ヘルスチェックをlivenessプロシージャ( @Liveness
修飾子付き)と定義したため、新しいヘルスチェックプロシージャが checks
配列に存在するようになりました。
おめでとうございます。初めてのQuarkus Health Checkプロシージャを作成しました。続けて、SmallRye Healthで他にどのようなことができるかを調べてみましょう。
レディネス・ヘルスチェック手順の追加
前のセクションでは、アプリケーションが実行されているかどうかを示す単純な liveness ヘルスチェックプロシージャを作成しました。このセクションでは、アプリケーションがリクエストを処理することができるかどうかを示すことができるReadinessヘルスチェックを作成します。
ここでは、データベースなどの外部サービスプロバイダへの接続をシミュレートする別のヘルスチェックプロシージャを作成します。まずは、アプリケーションの準備ができていることを示すレスポンスを常に返すようにします。
org.acme.microprofile.health.DatabaseConnectionHealthCheck
クラスを作成します。
package org.acme.microprofile.health;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Readiness;
import javax.enterprise.context.ApplicationScoped;
@Readiness
@ApplicationScoped
public class DatabaseConnectionHealthCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.up("Database connection health check");
}
}
http://localhost:8080/q/health/live`のヘルスチェックを再実行すると、 `checks
の配列には、以前に定義した SimpleHealthCheck
のみが含まれます。これは @Liveness
という修飾子で定義された唯一のチェックだからです。しかし、次のようにアクセスすると http://localhost:8080/q/health/ready
(ブラウザや curl http://localhost:8080/q/health/ready
)にアクセスすると、 Database connection health check
のみが表示されます。これは、Readinessヘルスチェックプロシージャとして @Readiness
の修飾子で定義された唯一のヘルスチェックだからです。
http://localhost:8080/q/health にアクセスすると、両方のチェックが戻ってきます。
|
どのような状況でどのヘルスチェックプロシージャを使用すべきかについての詳細は、MicroProfile Health 仕様に記載されています。一般的には、livenessプロシージャはアプリケーションを再起動すべきかどうかを判断し、readinessプロシージャはアプリケーションにリクエストを出すことが意味のあることかどうかを判断します。
スタートアップヘルスチェックプロシージャの追加
ヘルスチェックプロシージャの最後の3つ目のタイプはスタートアップです。スタートアッププロシージャは、起動が遅いコンテナ(Quarkusでは必要ないはず)のオプションとして定義されており、起動が初めてUPに応答すると起動から引き継がれるliveness probeの呼び出しを遅らせることができます。スタートアップのヘルスチェックは、 @Startup
で定義されます。
Please make sure that you import the microprofile org.eclipse.microprofile.health.Startup annotation since there is an unfortunate clash with io.quarkus.runtime.Startup .
|
org.acme.microprofile.health.SimpleHealthCheck
クラスを作成
package org.acme.microprofile.health;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Startup;
import javax.enterprise.context.ApplicationScoped;
@Startup
@ApplicationScoped
public class StartupHealthCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.up("Startup health check");
}
}
The startup health check will be available either at http://localhost:8080/q/health/started
or together with other health check procedure at http://localhost:8080/q/health
.
ネガティブヘルスチェックの手順
このセクションでは、 Database connection health check
を拡張して、基礎となるデータベース接続が確立できないために、アプリケーションがリクエストを処理する準備ができていないことを示すオプションを追加します。簡略化のため、データベースにアクセスできるかどうかの判断は、設定プロパティでのみ行います。
org.acme.microprofile.health.DatabaseConnectionHealthCheck
クラスを以下のように更新します。
package org.acme.microprofile.health;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
import org.eclipse.microprofile.health.Readiness;
import javax.enterprise.context.ApplicationScoped;
@Readiness
@ApplicationScoped
public class DatabaseConnectionHealthCheck implements HealthCheck {
@ConfigProperty(name = "database.up", defaultValue = "false")
private boolean databaseUp;
@Override
public HealthCheckResponse call() {
HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("Database connection health check");
try {
simulateDatabaseConnectionVerification();
responseBuilder.up();
} catch (IllegalStateException e) {
// cannot access the database
responseBuilder.down();
}
return responseBuilder.build();
}
private void simulateDatabaseConnectionVerification() {
if (!databaseUp) {
throw new IllegalStateException("Cannot contact database");
}
}
}
Until now, we used a simplified method of building a HealthCheckResponse through the HealthCheckResponse#up(String) (there is also HealthCheckResponse#down(String) ) which will directly build the response object. From now on, we utilize the full builder capabilities provided by the HealthCheckResponseBuilder class.
|
再度、Readinessヘルスチェック http://localhost:8080/q/health/ready
)を再実行すると、全ての status
がDOWNするはずです。また、以下の場所でlivenessチェックを行うこともできます。 http://localhost:8080/q/health/live`この場合、全体の `status
はUPです。これは、Readinessチェックの影響を受けないためです。
アプリケーションをReadinessチェックがDOWNの状態のままにしておくべきではない為、また、Quarkusを開発モードで実行しているため、 src/main/resources/application.properties
に database.up=true
を追加して、レディネスチェックを再実行してください。 — 再びUPになるはずです。
ヘルスチェックのレスポンスにユーザー固有のデータを追加
前のセクションでは、最小限の属性、すなわちヘルスチェック名とそのステータス(UPまたはDOWN)のみを持つ単純なヘルスチェックを作成する方法を説明しました。しかし、MicroProfile Health仕様では、アプリケーションが任意のデータを、コンシューマーに送信されるキー・バリュー・ペアの形で供給する方法も提供しています。これは、ヘルスチェックレスポンスビルダーAPIの withData(key, value)
メソッドを使用することで可能です。
新しいヘルスチェック・プロシージャ org.acme.microprofile.health.DataHealthCheck
を作成してみましょう。
package org.acme.microprofile.health;
import org.eclipse.microprofile.health.Liveness;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import javax.enterprise.context.ApplicationScoped;
@Liveness
@ApplicationScoped
public class DataHealthCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.named("Health check with data")
.up()
.withData("foo", "fooValue")
.withData("bar", "barValue")
.build();
}
}
/q/health/live
エンドポイントにアクセスしてLivenessヘルスチェック・プロシージャを再実行すると、新しいヘルスチェック Health check with data
が checks
配列に存在していることがわかります。このチェックには、 data
という新しい属性が含まれています。この属性は、ヘルスチェック手順で定義したプロパティで構成されるJSONオブジェクトです。
この機能は、ヘルスチェックの応答と一緒にエラーを渡すことができる障害シナリオで特に有用です。
try {
simulateDatabaseConnectionVerification();
responseBuilder.up();
} catch (IllegalStateException e) {
// cannot access the database
responseBuilder.down()
.withData("error", e.getMessage()); // pass the exception message
}
ヘルスチェック呼び出しへのコンテキストの伝搬
For performance reasons, the context (e.g., CDI or security context) is not propagated into each health check invocation. However, if you need to enable this functionality you can set the config property quarkus.smallrye-health.context-propagation=true
to allow the context propagation into every health check call.
リアクティブヘルスチェック
MicroProfile Healthは現在、リアクティブタイプのリターンをサポートしていませんが、SmallRye Healthはサポートしています。
リアクティブなヘルスチェックを行いたい場合は、 org.eclipse.microprofile.health.HealthCheck
の代わりに io.smallrye.health.api.AsyncHealthCheck
のインターフェイスを実装することができます。 io.smallrye.health.api.AsyncHealthCheck
インターフェイスでは、 Uni<HealthCheckResponse>
を返すことができます。
以下の例では、リアクティブなLivenessチェックを行っています。
import io.smallrye.health.api.AsyncHealthCheck;
import org.eclipse.microprofile.health.Liveness;
import org.eclipse.microprofile.health.HealthCheckResponse;
import javax.enterprise.context.ApplicationScoped;
@Liveness
@ApplicationScoped
public class LivenessAsync implements AsyncHealthCheck {
@Override
public Uni<HealthCheckResponse> call() {
return Uni.createFrom().item(HealthCheckResponse.up("liveness-reactive"))
.onItem().delayIt().by(Duration.ofMillis(10));
}
}
エクステンションのヘルスチェック
一部のエクステンションでは、デフォルトのヘルスチェックを提供している場合があり、その場合、エクステンションは自動的にヘルスチェックを登録します。
例えば、Quarkusのデータソースを管理するために使用される quarkus-agroal
は、各 データソースのヘルスチェックを検証するReadinessのヘルスチェックを自動的に登録します。 。
エクステンションのヘルスチェックは、プロパティ( quarkus.health.extensions.enabled
)で無効にすることができ、自動的に登録されることはありません。
Health UI
実験的 - MicroProfileの仕様に含まれない |
health-ui
はヘルスチェックの内容をWeb GUIで確認することができます。
Quarkusの smallrye-health
エクステンションは、 health-ui
を同梱しており、devおよびtestモードでデフォルトで有効になりますが、productionモードでも同様に明示的に設定することができます。
health-ui
は、 http://localhost:8080/q/health-ui/ からアクセスできます。
まとめ
SmallRye Health provides a way for your application to distribute information about its healthiness state to state whether it is able to function properly. Liveness checks are utilized to tell whether the application should be restarted and readiness checks are used to tell whether the application is able to process requests.
QuarkusでSmallRye Healthの機能を有効にするために必要なのは
-
quarkus-maven-plugin
でsmallrye-health
Quarkusエクステンションをプロジェクトに追加:CLIquarkus extension add 'smallrye-health'
Maven./mvnw quarkus:add-extension -Dextensions="smallrye-health"
Gradle./gradlew addExtension --extensions="smallrye-health"
-
または、単に以下のMaven依存関係を追加するだけです:
pom.xml<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-health</artifactId> </dependency>
build.gradleimplementation("io.quarkus:quarkus-smallrye-health")
設定リファレンス
ビルド時に固定される設定プロパティ - それ以外の設定プロパティは実行時に上書き可能
タイプ |
デフォルト |
|
---|---|---|
Whether extensions published health check should be enabled. Environment variable: |
boolean |
|
Whether to include the Liveness and Readiness Health endpoints in the generated OpenAPI document Environment variable: |
boolean |
|
Root path for health-checking endpoints. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
The relative path of the liveness health-checking endpoint. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
The relative path of the readiness health-checking endpoint. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
The relative path of the health group endpoint. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
The relative path of the wellness health-checking endpoint. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
The relative path of the startup health-checking endpoint. By default, this value will be resolved as a path relative to Environment variable: |
string |
|
Whether the context should be propagated to each health check invocation. Environment variable: |
boolean |
|
If Health UI should be enabled. By default, Health UI is enabled if it is included (see Environment variable: |
boolean |
|
Additional top-level properties to be included in the resulting JSON object. Environment variable: |
|
|
Whether the HealthCheck should be enabled. Environment variable: |
boolean |
|
タイプ |
デフォルト |
|
The path where Health UI is available. The value Environment variable: |
string |
|
Always include the UI. By default, this will only be included in dev and test. Setting this to true will also include the UI in Prod Environment variable: |
boolean |
|