概要
Spring Bootのactuatorで取得できるhealthの情報をBeanで利用する方法を調べたのでシェア
用途は、actuatorのhealthが、アプリケーションの環境(diskやDBの接続状態)の情報を表すのに対し、サービス固有のスタンバイ状態などを表現したい場合に使えます。
例えば、k8sのreadinessとlivenessを使い分けたいときなどに利用できます。
参考
Introducing Actuator Endpoints in Spring Boot 2.0
Spring Boot on Kubernetes : Yahoo!ズバトク事例
やり方
RouterFunction(かつKotlin)を使った例になっていますが、アノテーションベースでも動くはずです。
package com.example.service
import org.springframework.boot.actuate.health.HealthEndpoint
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.status
import org.springframework.web.reactive.function.server.body
import reactor.core.publisher.Mono
@Component
class StatusService(
private val healthEndpoint: HealthEndpoint
) {
private var ready: Boolean = false
fun ready() = ready
fun readiness(req: ServerRequest): Mono<ServerResponse> {
if (!this.ready || healthEndpoint.health().status.code != "UP") {
return status(HttpStatus.SERVICE_UNAVAILABLE).body(Mono.just("service is unavailable"))
}
return status(HttpStatus.OK).body(Mono.just("service is available"))
}
fun serviceIn() {
this.ready = true
}
fun serviceOut() {
this.ready = false
}
}