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

shabinjo picture shabinjo · Jun 30, 2017 · Viewed 48.5k times · Source
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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
    }
}

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

Answer

shabinjo picture shabinjo · Jun 30, 2017

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();
        }
    }
}

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
    }
}