如何在Spring Boot运行状况中添加自定义运行状况检查? [英] How to add a custom health check in spring boot health?

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

问题描述

<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运行状况中添加自定义运行状况检查?

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运行状况中添加自定义运行状况检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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