Spring Boot Actuator - アプリケーション状態確認、モニタリング支援機能
概要
ここでは、さまざまなモニタリングおよび管理目的でBootアプリケーションに使用できる組み込みHTTPエンドポイントについて見ていく。Spring Framework以前は、アプリケーションにこの種のモニタリング機能を導入する必要がある場合、これらすべてのコンポーネントを手動で開発する必要があり、しかも必要不可欠な機能でもあった。しかし、Spring Bootにはモニタリング機能を非常に簡単に作成できるActuatorモジュールがある。
いくつか設定するだけで完了し、すべての管理およびモニタリング関連情報を簡単に利用できる。Spring Boot 2 Actuator Endpointを構成する方法を見ていく。
Spring Boot Actuator Module
Spring Bootのモジュールを使用すると、Actuatorのコーディングや構成なしで、運用環境におけるアプリケーション利用状況をモニタリングおよび管理できる。これらのモニタリングおよび管理情報は、endpoint URLのようなRESTを通じて公開される。
Actuator依存関係
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
}
重要なActuator Endpoint
ほとんどのアプリケーションでは、/actuatorプレフィックスとともにエンドポイントのIDがURLにマッピングされるHTTP経由でエンドポイントを公開する。たとえば、デフォルトではヘルスエンドポイントは/actuator/healthにマッピングされる。
重要でよく使用されるActuatorエンドポイントは次のとおりである。
| エンドポイント | 説明 |
|---|---|
/auditevents |
すべての自動構成候補と、その候補が「適用」または「適用されなかった」理由を返す。 |
/beans |
アプリケーション内にあるすべてのSpring beansの完全な一覧を返す。 |
/mappings |
すべての@RequestMapping.パスの結合された一覧を返す。 |
/env |
現在の環境のプロパティ一覧を返す。 |
/health |
アプリケーションの状態情報を返す。 |
/caches |
使用可能なキャッシュを返す。 |
/conditions |
構成および自動構成で評価された条件を返す。 |
/configprops |
すべての@ConfigurationPropertiesを返す。 |
/Intergrationgraph |
Spring Integrationグラフを表示する。spring-intergration-coreへの依存関係が必要である。 |
/loggers |
アプリケーションのLogger構成。 |
/scheduledtasks |
アプリケーション内で予約されたタスクを返す。 |
/sessions |
トレースログを表示する(デフォルトでは最後の100個のHTTPリクエスト)。HttpTraceRepository Beanが必要である。 |
/httptrace |
Spring Session対応のセッションストアからユーザーセッションを検索、削除できる。Spring Sessionを使用するServletベースのWebアプリケーションが必要である。 |
/shutdown |
アプリケーションを正常終了できる。デフォルトでは無効である。 |
/threaddump |
thread dumpを実行する。 |
/metrics |
使用されたJVMメモリ、システムCPU使用率、開いているファイルなど、いくつかの有用なメトリクス情報を表示する。 |
Spring Webアプリケーション(Spring MVC、Spring WebFlux、またはJersey)は、次の追加エンドポイントを提供する。
| エンドポイント | 説明 |
|---|---|
/heapdump |
hprofヒープダンプファイルを返す。 |
/logfile |
logging.file.nameまたはlogging.file.path属性が設定されている場合、ログファイルの内容を表示する。 |
エンドポイントセキュリティ
デフォルトでは、クラスパスで利用可能な場合、すべてのActuatorエンドポイントに対してSpring Securityが有効になる。
たとえば、HTTPエンドポイントに対してカスタムセキュリティを構成し、特定のロールを持つユーザーだけがアクセスできるようにするには、次のようにWebSecurityConfigurerAdapterを設定する。
@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
}
}
上記の構成は、ENDPOINT_ADMINロールを持つユーザーだけが動作中のエンドポイントへアクセスできるようにする。
エンドポイントの有効化
デフォルトでは、すべてのエンドポイント(/shutdownを除く)が有効である。すべてのエンドポイントを無効にするには、次のように属性を設定する。
management.endpoints.enabled-by-default=false
その後、アプリケーションで使用したいエンドポイントを、management.endpoint.{id}.enabled.パターンで有効化する。
management.endpoint.health.enabled=true
management.endpoint.loggers.enabled=true
CORS対応
CORS対応はデフォルトでは無効であり、.management.endpoints.cors.allowed-origins属性を設定すると有効になる。
management.endpoints.web.cors.allowed-origins=https://example.com
management.endpoints.web.cors.allowed-methods=GET,POST
ここで管理コンテキストパスは/managementである。
レスポンスキャッシュ
Actuatorエンドポイントは、パラメータを使用しない読み取り操作のレスポンスを自動的にキャッシュする。cache.time-to-live属性は、エンドポイントがレスポンスをキャッシュする時間を設定するために使用される。
management.endpoint.beans.cache.time-to-live=20s
Spring Boot Actuatorプロジェクト作成
それでは、簡単なSpring Bootアプリケーションのサンプルプロジェクトを作成してみる。この例でActuatorエンドポイントへアクセスし、詳細を確認できる。
新規プロジェクト作成コマンド
次のようにcurlコマンドを使って、Spring Bootの新規プロジェクトを作成する。
curl https://start.spring.io/starter.tgz \
-d bootVersion=2.7.6 \
-d dependencies=web,actuator \
-d baseDir=spring-actuator \
-d groupId=com.devkuma \
-d artifactId=spring-actuator \
-d packageName=com.devkuma.actuator \
-d applicationName=ActuatorApplication \
-d javaVersion=11 \
-d packaging=jar \
-d type=gradle-project | tar -xzvf -
このコマンドでは、Java 11、Gradle、Spring Boot 2.7.6を使用し、依存関係として「web,actuator」を追加している。
簡単なRESTエンドポイント追加
次に、簡単なRESTエンドポイント/helloをアプリケーションに追加する。
package com.devkuma.actuator;
import java.util.Date;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloRestController {
@GetMapping("/hello")
public String hello() {
return "Hello User !! " + new Date();
}
}
すべてのエンドポイント公開設定
Web API経由ですべてのエンドポイントを公開するため、次のように設定ファイル(application.properties)を追加する。
management.endpoints.web.exposure.include=*
Spring Boot Actuator起動
それでは、プロジェクトを起動してみる。
エンドポイント環境出力
- http://localhost:8080/actuator/env
- このURLでは、サーバーに関するすべての環境構成内容が提供される。
{
"activeProfiles": [],
"propertySources": [
{
"name": "server.ports",
"properties": {
"local.server.port": {
"value": 8080
}
}
},
{
"name": "servletContextInitParams",
"properties": {}
},
{
"name": "systemProperties",
"properties": {
"gopherProxySet": {
"value": "false"
},
"awt.toolkit": {
"value": "sun.lwawt.macosx.LWCToolkit"
},
"java.specification.version": {
"value": "11"
},
"sun.cpu.isalist": {
"value": ""
},
... 以下省略 ...
エンドポイントbean出力
- http://localhost:8080/actuator/beans
- このURLでは、コンテキストにロードされたすべてのSpring Bean一覧が提供される。
{
"contexts": {
"application": {
"beans": {
"endpointCachingOperationInvokerAdvisor": {
"aliases": [],
"scope": "singleton",
"type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
"resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
"dependencies": [
"org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration",
"environment"
]
},
"defaultServletHandlerMapping": {
"aliases": [],
"scope": "singleton",
"type": "org.springframework.web.servlet.HandlerMapping",
"resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
"dependencies": [
"org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration"
]
},
... 以下省略 ...
エンドポイントスレッドダンプ出力
- http://localhost:8080/actuator/threaddump
- このURLでは、現在のサーバースレッドダンプが提供される。
{
"threads": [
{
"threadName": "Reference Handler",
"threadId": 2,
"blockedTime": -1,
"blockedCount": 5,
"waitedTime": -1,
"waitedCount": 0,
"lockName": null,
"lockOwnerId": -1,
"lockOwnerName": null,
"daemon": true,
"inNative": false,
"suspended": false,
"threadState": "RUNNABLE",
"priority": 10,
"stackTrace": [
{
"classLoaderName": null,
"moduleName": "java.base",
"moduleVersion": "11.0.16.1",
"methodName": "waitForReferencePendingList",
"fileName": "Reference.java",
"lineNumber": -2,
"className": "java.lang.ref.Reference",
"nativeMethod": true
},
... 以下省略 ...
これらのエンドポイントは、ブラウザに標準情報を提供する。ここでは一般的によく参照する基本的な重要エンドポイントをいくつか紹介したが、Spring Bootはこのリンクで言及されているように、さらに多くのエンドポイントを提供している。
Actuator高度な構成オプション
管理エンドポイントコンテキストパス変更
デフォルトでは、すべてのエンドポイントは/actuatorで始まるアプリケーションの基本コンテキストパスに提供される。何らかの理由で、アプリケーションに/actuatorで始まる既存エンドポイントがある場合、基本パスを別のものに変更できる。
application.propertiesに新しい基本パスを指定するだけでよい。
management.endpoints.web.base-path=/manage
これで、新しいURLからすべてのActuatorエンドポイントへアクセスできる。たとえば、次のようになる。
- /manage/health
- /manage/dump
- /manage/env
- /manage/beans
管理サーバーポート変更
管理エンドポイントのポートを変更するには、application.properties設定ファイルにこの項目を追加すればよい。
management.server.port=8081
まとめ
このSpring Boot Actuatorプロジェクト例では、いくつかの簡単な構成で管理およびモニタリングエンドポイントを構成する方法を学んだ。
プロジェクト作成時にアプリケーション状態確認機能やモニタリング支援を追加する必要があるなら、Spring Actuatorの導入を検討するのも良い方法だろう。
参考
- 上記の完成済みプロジェクトコードはこちらに置いてある。