基礎編
Spring Actuatorとは何か?
Spring Bootのspring-boot-starter-actuatorモジュールは、Springが提供する監視機能です。開発・運用プロセスにおいて、アプリケーションの各種状態と可用性をリアルタイムまたは定期的に監視する必要があります。Spring Bootのspring-boot-starter-actuatorモジュール(健康監視機能)は、多くの監視に必要なインターフェースを提供し、アプリケーションシステムの設定確認や関連機能の統計などを行うことができます。
コード実装
Mavenのpom.xmlに依存関係を追加:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
application.ymlファイルに設定を追加:
server:
port: 8080 #サービスポート
spring:
application:
name: server-actuator
management:
server:
port: 8081 #actuatorポート
endpoints:
web:
base-path: /
exposure:
include: "*"
ブラウザでhttp://localhost:8081/healthにアクセスするとJSON文字列が取得できますが、これはビジネスシーンには適していません。次の応用編では、UI付きのコンポーネントを紹介します。
応用編:SpringBoot Admin(SBA)によるSpring BootのUI監視
SBAとは?
SBAはActuatorをさらに進化させたもので、ActuatorインターフェースをUIで美化してラップした監視ツールです。Spring Boot Adminは、Spring Bootアプリケーションを管理・監視するオープンソースソフトウェアです。各アプリケーションはクライアントとしてHTTPまたはEurekaを使用してadminサーバーに登録され、表示されます。Spring Boot Admin UI部分はAngularJsを使用してデータをフロントエンドで表示します。
フロントエンドのUIは以下のようになります:
これにより、サービスの稼働状況が一目瞭然になります。
コード実装
(1)サービスの構築
Adminサービス(管理サーバー)、Service01、Service02の3つのサービスを作成します。ここでAdminサービスはService01とService02を管理します。プロジェクト構造は以下のようになります:
(2)Adminサービスのpom.xmlとapplication.ymlに以下の内容を追加:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
</dependency>
</dependencies>
server:
port: 8080 #サービスポート
spring:
application:
name: server-admin
management:
server:
port: 8081 #actuatorポート
endpoints:
web:
base-path: /
exposure:
include: "*"
スタートアップクラスに@EnableAdminServerアノテーションを追加します。
(3)Service01、Service02サービスのpom.xml、application.ymlに以下の内容を追加:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>
</dependencies>
server:
port: 9666
management:
metrics:
web:
server:
auto-time-requests: false
endpoints:
web:
exposure:
include: '*'
exclude: env,beans
spring:
boot:
admin:
client:
url: http://localhost:8080 #管理サービスのURL
instance: service01 #監視サービス名
application:
name: service01
これですべてのプロジェクトを起動し、http://localhost:8080/にアクセスすると監視画面が表示されます。