Spring Boot Health Check API Using Actuator + ThirdParty Api Status
Introduction:
In a microservices architecture, ensuring the health of your services is critical. A health check API enables you to monitor and maintain the reliability of your system. In this post, we’ll look at how to build a Health Check API in the Spring Boot Application.
Code Overview:
HealthCheckController:
- This controller exposes two endpoints (
/api/health-check
&/api/ping
endpoint) - The
/ping
endpoint returns a simple “OK” response. - The main health check endpoint returns the health status obtained from the Spring Boot Actuator’s
HealthEndpoint
.
@GetMapping(value = "/ping")
public ResponseEntity<String> ping() {
return ResponseEntity.ok("{\"status\":\"OK\"}");
}
@GetMapping(value = {"", "/"})
public ResponseEntity<String> check() {
String health = healthEndpoint.health().getStatus().getCode();
return ResponseEntity.ok("{\"status\":\"" + health + "\"}");
}
ThirdPartyHealthCheck:
- This class implements the Spring Boot
HealthIndicator
interface to create a custom health check for a third-party service. - The
health()
method returns a health status with additional details.
@Override
public Health health() {
Map<String, Object> details = new HashMap<>();
details.put("chance", "something");
// return Health.down().withDetails(details).build(); // in case of failure
return Health.up().withDetails(details).build();
}
Sample Request and Response:
Success Response:
{
"status": "UP"
}
Error Response:
{
"status": "DOWN"
}
In this article, we explored how to create a Spring Boot Health Check API, including custom health indicators for third-party services. Implementing a simple health check is important for maintaining the reliability and stability of your microservices architecture.
You can still get details by using this internal endpoint
http://localhost:8080/management/health
The GitHub Code can be found here :)