Custom health indicator

Spring Boot Actuator's health endpoint is really helpful for checking the status of Spring Boot application and dependent systems such as databases, message queues, and so on. Spring Boot ships out of the box with many standard HealthIndicator implementations such as DiskSpaceHealthIndicator, DataSourceHealthIndicator, and MailHealthIndicatorwhich can all be used in Spring Boot applications with Spring Boot Actuator. Furthermore, custom health indicators can also be implemented if required:

public class InternetHealthIndicator implements HealthIndicator {

private static final Logger LOGGER = LoggerFactory.getLogger(InternetHealthIndicator.class);

public static final String UNIVERAL_INTERNET_CONNECTIVITY_CHECKING_URL = "https://www.google.com";

private final RestTemplate restTemplate;

public InternetHealthIndicator(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}

@Override
public Health health() {
try {
ResponseEntity<String> response = restTemplate.getForEntity(UNIVERAL_INTERNET_CONNECTIVITY_CHECKING_URL, String.class);
LOGGER.info("Internet Health Response Code {}",
response.getStatusCode());
if (response.getStatusCode().is2xxSuccessful()) {
return Health.up().build();
}
} catch (Exception e) {
LOGGER.error("Error occurred while checking
internet connectivity"
, e);
return Health.down(e).build();
}

return Health.down().build();
}
}

The preceding InternetHealthIndicator is intended to show the status of internet connectivity from within Spring Boot applications to the outside world. It will send a request to www.google.com to check whether it sends a successful HTTP response code, and based on that the health status of this indicator will be set to up or down. This was injected as a Spring Bean using an ApplicationContextInitializer earlier. Invoking the http://<host>:<port>/actuator/health URL will return the internet status as in the following:

{  
"status":"UP",
"details":{
"internet":{
"status":"UP"
},
"diskSpace":{
"status":"UP",
"details":{
"total":399268376576,
"free":232285409280,
"threshold":10485760
}
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221