Spring Boot Health Checks

Spring Boot brings along some cool “production ready” features. Among them are the health checks. They are a great way to give you a quick overview about the system state. Is the database up and running, is my disk running out of space?

Getting started

Having a Spring Boot application already setup you just have to add the dependency for the Spring Boot Actuator.

<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":7537176576,"threshold":10485760}}

Add a custom health check

Adding a custom health check is pretty 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 SomeServiceHealthCheck 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","someServiceHealthCheck":{"status":"UP"},"diskSpace":{"status":"UP","free":7536922624,"threshold":10485760}}

Add a better view

For a quick overview the health checks are great, but no one from your operating team will love reading through the JSON result of the /health endpoint. Better create some view and present the data in a much more human readable way. I personally like the apporach jHipster has implemented for their health checks.

healthcheck

Conclusion

Personally speaking Spring Boot is the right step forward for the Spring framework. The production ready features offered, especially the health checks, are great to quickly locate connectivity issues and can give you an overall better feeling in production environments where you might not be able to analyze issues quickly due to access restrictions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.