HealthIndicator cho phép thêm custom health check vào /actuator/health — quan trọng cho Kubernetes liveness/readiness probe.
java
@Component("externalApi")
class ExternalApiHealthIndicator implements HealthIndicator {
private final RestClient restClient;
@Override
public Health health() {
try {
ResponseEntity<String> resp = restClient.get()
.uri("https://api.external.com/health")
.retrieve().toEntity(String.class);
if (resp.getStatusCode().is2xxSuccessful()) {
return Health.up().withDetail("status", "reachable").build();
}
return Health.down().withDetail("statusCode", resp.getStatusCode()).build();
} catch (Exception e) {
return Health.down(e).withDetail("message", "External API unreachable").build();
}
}
}Kết quả /actuator/health:
json
{"status":"DOWN","components":{"externalApi":{"status":"DOWN"}}}Liveness vs Readiness (Kubernetes):
yaml
management:
endpoint.health.group:
liveness.include: livenessState
readiness.include: readinessState, db, externalApi/actuator/health/readiness → DOWN → K8s dừng route traffic đến pod.
HealthIndicator lets you add custom health checks to /actuator/health — important for Kubernetes liveness/readiness probes.
java
@Component("externalApi")
class ExternalApiHealthIndicator implements HealthIndicator {
private final RestClient restClient;
@Override
public Health health() {
try {
ResponseEntity<String> resp = restClient.get()
.uri("https://api.external.com/health")
.retrieve().toEntity(String.class);
if (resp.getStatusCode().is2xxSuccessful()) {
return Health.up().withDetail("status", "reachable").build();
}
return Health.down().withDetail("statusCode", resp.getStatusCode()).build();
} catch (Exception e) {
return Health.down(e).withDetail("message", "External API unreachable").build();
}
}
}/actuator/health response:
json
{"status":"DOWN","components":{"externalApi":{"status":"DOWN"}}}Liveness vs Readiness (Kubernetes):
yaml
management:
endpoint.health.group:
liveness.include: livenessState
readiness.include: readinessState, db, externalApi/actuator/health/readiness → DOWN → K8s stops routing traffic to the pod.