Skip to content

15.3.2 Defining custom health indicators

Spring Boot comes with several out-of-the-box health indicators that provide health information for many common external systems that a Spring application may integrate with. But at some point, you may find that you’re interacting with some external system that Spring Boot neither anticipated nor provided a health indicator for.

For instance, your application may integrate with a legacy mainframe application, and the health of your application may be affected by the health of the legacy system. To create a custom health indicator, all you need to do is create a bean that implements the HealthIndicator interface.

As it turns out, the Taco Cloud services have no need for a custom health indicator, because the ones provided by Spring Boot are more than sufficient. But to demonstrate how you can develop a custom health indicator, consider the next listing, which shows a simple implementation of HealthIndicator in which health is determined somewhat randomly by the time of day.

Listing 15.5 An unusual implementation of HealthIndicator

java
package tacos.tacos;
import java.util.Calendar;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class WackoHealthIndicator implements HealthIndicator {
@Override
  public Health health() {
    int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    if (hour > 12) {
        return Health
            .outOfService()
            .withDetail("reason",
                "I'm out of service after lunchtime")
            .withDetail("hour", hour)
            .build();
    }
    if (Math.random() < 0.1) {
        return Health
            .down()
            .withDetail("reason", "I break 10% of the time")
            .build();
    }
    return Health
        .up()
        .withDetail("reason", "All is good!")
        .build();
  }
}

This crazy health indicator first checks what the current time is, and if it’s after noon, returns a health status of OUT\_OF\_SERVICE, with a few details explaining the reason for that status. Even if it’s before lunch, there’s a 10% chance that the health indicator will report a DOWN status, because it uses a random number to decide whether or not it’s up. If the random number is less than 0.1, the status will be reported as DOWN. Otherwise, the status will be UP.

Obviously, the health indicator in listing 15.5 isn’t going to be very useful in any real-world applications. But imagine that instead of consulting the current time or a random number, it were to make a remote call to some external system and determine the status based on the response it receives. In that case, it would be a very useful health indicator.

Released under the MIT License.