如何在 spring boot health 中添加自定义健康检查? [英] How to add a custom health check in spring boot health?

查看:57
本文介绍了如何在 spring boot health 中添加自定义健康检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

这将为您的应用程序添加几个有用的端点.其中之一是/health.当您启动应用程序并导航到/health 端点时,您会看到它已经返回了一些数据.

This will add several useful endpoints to your application. One of them is /health. When you start your application and navigate to the /health endpoint you will see it returns already some data.

{
    "status":"UP",
    "diskSpace": {
        "status":"UP",
        "free":56443746,
        "threshold":1345660
    }
}

如何在spring boot health中添加自定义健康检查?

How to add a custom health check in spring boot health?

推荐答案

添加自定义运行状况检查很容易.只需创建一个新的 Java 类,从 AbstractHealthIndicator 扩展它并实现 doHealthCheck 方法.该方法获取一个带有一些有用方法的构建器.如果您的健康状况良好,则调用 builder.up(),否则调用 builder.down().您如何检查健康完全取决于您.也许你想 ping 一些服务器或检查一些文件.

Adding a custom health check is easy. Just create a new Java class, extend it from the AbstractHealthIndicator and implement the doHealthCheck method. The method gets a builder passed with some useful methods. Call builder.up() if your health is OK or builder.down() if it is not. What you do to check the health is completely up to you. Maybe you want to ping some server or check some files.

@Component
public class CustomHealthCheck extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder bldr) throws Exception {
        // TODO implement some check
        boolean running = true;
        if (running) {
          bldr.up();
        } else {
          bldr.down();
        }
    }
}

这足以激活新的健康检查(确保@ComponentScan 在您的应用程序中).重新启动您的应用程序并将您的浏览器定位到/health 端点,您将看到新添加的健康检查.

This is enough to activate the new health check (make sure @ComponentScan is on your application). Restart your application and locate your browser to the /health endpoint and you will see the newly added health check.

{
    "status":"UP",
    "CustomHealthCheck": {
        "status":"UP"
    },
    "diskSpace": {
        "status":"UP",
        "free":56443746,
        "threshold":1345660
    }
}

这篇关于如何在 spring boot health 中添加自定义健康检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆