Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Spring Bootのactuatorで取得できるhealthの情報をBeanで利用する

More than 1 year has passed since last update.

概要

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
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away