Capítulo 4: Health Checks
Introdução
Os Health Checks permitem verificar se sua aplicação e suas dependências estão funcionando corretamente. Essenciais para load balancers, Kubernetes e monitoramento.
🎯 Objetivos do Capítulo
Ao final deste capítulo, você saberá:
- ✅ Compreender os health indicators nativos
- ✅ Criar health checks personalizados
- ✅ Configurar grupos de saúde
- ✅ Implementar liveness e readiness probes
1. Health Check Básico
Configuração
# Exibir detalhes
management.endpoint.health.show-details=always
# Opções: never, when_authorized, always
Resposta
curl http://localhost:8080/actuator/health
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "H2",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 499963174912,
"free": 234567891234,
"threshold": 10485760,
"path": "/app/.",
"exists": true
}
},
"ping": {
"status": "UP"
}
}
}
Status Possíveis
| Status | Descrição | HTTP Code |
|---|---|---|
UP | Tudo funcionando | 200 |
DOWN | Algo não está funcionando | 503 |
OUT_OF_SERVICE | Fora de serviço (manutenção) | 503 |
UNKNOWN | Estado desconhecido | 200 |
2. Health Indicators Nativos
O Spring Boot inclui health indicators automáticos:
| Indicator | Detectado se... |
|---|---|
DataSourceHealthIndicator | DataSource configurado |
DiskSpaceHealthIndicator | Sempre ativo |
MongoHealthIndicator | MongoDB configurado |
RedisHealthIndicator | Redis configurado |
RabbitHealthIndicator | RabbitMQ configurado |
ElasticsearchHealthIndicator | Elasticsearch configurado |
MailHealthIndicator | Mail configurado |
Desativar um Indicator
# Desativar o check de espaço em disco
management.health.diskspace.enabled=false
# Desativar o check do banco de dados
management.health.db.enabled=false
3. Health Check Personalizado
Implementação Simples
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {
private final ExternalApiClient apiClient;
public ExternalApiHealthIndicator(ExternalApiClient apiClient) {
this.apiClient = apiClient;
}
@Override
public Health health() {
try {
boolean isUp = apiClient.ping();
if (isUp) {
return Health.up()
.withDetail("api", "external-api")
.withDetail("status", "reachable")
.build();
} else {
return Health.down()
.withDetail("api", "external-api")
.withDetail("status", "unreachable")
.build();
}
} catch (Exception e) {
return Health.down()
.withDetail("api", "external-api")
.withDetail("error", e.getMessage())
.build();
}
}
}
Resultado
{
"status": "UP",
"components": {
"externalApi": {
"status": "UP",
"details": {
"api": "external-api",
"status": "reachable"
}
}
}
}
Health Check com Limiares
@Component
public class QueueHealthIndicator implements HealthIndicator {
private final TaskQueue taskQueue;
private static final int WARNING_THRESHOLD = 100;
private static final int CRITICAL_THRESHOLD = 500;
public QueueHealthIndicator(TaskQueue taskQueue) {
this.taskQueue = taskQueue;
}
@Override
public Health health() {
int queueSize = taskQueue.size();
Health.Builder builder = new Health.Builder()
.withDetail("queueSize", queueSize)
.withDetail("warningThreshold", WARNING_THRESHOLD)
.withDetail("criticalThreshold", CRITICAL_THRESHOLD);
if (queueSize >= CRITICAL_THRESHOLD) {
return builder.down()
.withDetail("message", "Queue is critically full!")
.build();
} else if (queueSize >= WARNING_THRESHOLD) {
return builder.status("WARNING")
.withDetail("message", "Queue is getting full")
.build();
} else {
return builder.up()
.withDetail("message", "Queue is healthy")
.build();
}
}
}
Health Check Assíncrono
Para evitar bloqueio caso o check seja lento:
@Component
public class SlowServiceHealthIndicator implements HealthIndicator {
private final SlowService slowService;
private volatile Health cachedHealth = Health.unknown().build();
@Scheduled(fixedRate = 30000) // A cada 30 segundos
public void checkHealth() {
try {
boolean isUp = slowService.ping();
cachedHealth = isUp
? Health.up().withDetail("lastCheck", Instant.now()).build()
: Health.down().withDetail("lastCheck", Instant.now()).build();
} catch (Exception e) {
cachedHealth = Health.down()
.withDetail("error", e.getMessage())
.withDetail("lastCheck", Instant.now())
.build();
}
}
@Override
public Health health() {
return cachedHealth; // Retorna imediatamente o cache
}
}
4. Grupos de Saúde
Configuração de Grupos
# Grupo para o load balancer (checks rápidos)
management.endpoint.health.group.liveness.include=ping
management.endpoint.health.group.liveness.show-details=never
# Grupo para readiness do Kubernetes (checks completos)
management.endpoint.health.group.readiness.include=db,redis,externalApi
management.endpoint.health.group.readiness.show-details=when_authorized
# Grupo para monitoramento (todos)
management.endpoint.health.group.full.include=*
management.endpoint.health.group.full.show-details=always
Acessando os Grupos
# Check básico
curl http://localhost:8080/actuator/health
# Grupo liveness
curl http://localhost:8080/actuator/health/liveness
# Grupo readiness
curl http://localhost:8080/actuator/health/readiness
# Grupo completo
curl http://localhost:8080/actuator/health/full
5. Kubernetes: Liveness vs Readiness
Conceitos
Liveness Probe:
"O aplicativo está vivo?"
→ Se DOWN: Kubernetes reinicia o pod
Readiness Probe:
"O aplicativo está pronto para receber tráfego?"
→ Se DOWN: Kubernetes remove o pod do load balancer
Configuração Spring Boot
# Ativar probes do Kubernetes
management.endpoint.health.probes.enabled=true
# Grupos automáticos criados:
# /actuator/health/liveness
# /actuator/health/readiness
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
template:
spec:
containers:
- name: my-app
image: my-app:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 3
Personalizar os Grupos
@Component
public class CustomLivenessIndicator implements HealthIndicator {
@Override
public Health health() {
// Verificação mínima: o app responde
return Health.up().build();
}
}
@Component
public class CustomReadinessIndicator implements HealthIndicator {
private final DataSource dataSource;
private final RedisTemplate<?, ?> redis;
@Override
public Health health() {
// Verificar se as dependências estão prontas
try {
dataSource.getConnection().isValid(1);
redis.getConnectionFactory().getConnection().ping();
return Health.up().build();
} catch (Exception e) {
return Health.down().withException(e).build();
}
}
}
management.endpoint.health.group.liveness.include=customLiveness,ping
management.endpoint.health.group.readiness.include=customReadiness,db,redis
6. Health Check para Load Balancer
Endpoint Dedicado Simples
@RestController
public class HealthController {
private final AtomicBoolean healthy = new AtomicBoolean(true);
@GetMapping("/health/lb")
public ResponseEntity<String> lbHealthCheck() {
if (healthy.get()) {
return ResponseEntity.ok("OK");
}
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("DOWN");
}
// Para manutenção: colocar o app fora de serviço
@PostMapping("/admin/maintenance/enable")
public void enableMaintenance() {
healthy.set(false);
}
@PostMapping("/admin/maintenance/disable")
public void disableMaintenance() {
healthy.set(true);
}
}
7. Resumo
Configuração Recomendada
# Detalhes conforme autorização
management.endpoint.health.show-details=when_authorized
management.endpoint.health.show-components=when_authorized
# Ativar probes K8s
management.endpoint.health.probes.enabled=true
# Grupos personalizados
management.endpoint.health.group.liveness.include=ping,livenessState
management.endpoint.health.group.readiness.include=readinessState,db,redis
Health Indicator Personalizado
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health() {
if (isHealthy()) {
return Health.up()
.withDetail("key", "value")
.build();
}
return Health.down()
.withDetail("error", "Something wrong")
.build();
}
}
Grupos Kubernetes
| Grupo | Uso | Include |
|---|---|---|
liveness | Pod está vivo? | ping, basic checks |
readiness | Pronto para tráfego? | db, redis, external APIs |
🎯 Próximo Passo
Hora da prática! Vamos configurar o Actuator de A a Z.
➡️ TP11.1: Configuração do Actuator