Aller au contenu principal

Chapitre 4: Health Checks

Introduction​

Les Health Checks permettent de vérifier si votre application et ses dépendances fonctionnent correctement. Essentiels pour les load balancers, Kubernetes, et le monitoring.


🎯 Objectifs du Chapitre​

À la fin de ce chapitre, vous saurez:

  1. ✅ Comprendre les health indicators natifs
  2. ✅ Créer des health checks personnalisés
  3. ✅ Configurer les groupes de santé
  4. ✅ Implémenter liveness et readiness probes

1. Health Check de Base​

Configuration​

# Afficher les détails
management.endpoint.health.show-details=always

# Options: never, when_authorized, always

Réponse​

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 Possibles​

StatusDescriptionHTTP Code
UPTout fonctionne200
DOWNQuelque chose ne marche pas503
OUT_OF_SERVICEHors service (maintenance)503
UNKNOWNÉtat inconnu200

2. Health Indicators Natifs​

Spring Boot inclut des health indicators automatiques:

IndicatorDétecté si...
DataSourceHealthIndicatorDataSource configuré
DiskSpaceHealthIndicatorToujours actif
MongoHealthIndicatorMongoDB configuré
RedisHealthIndicatorRedis configuré
RabbitHealthIndicatorRabbitMQ configuré
ElasticsearchHealthIndicatorElasticsearch configuré
MailHealthIndicatorMail configuré

Désactiver un Indicator​

# Désactiver le check d'espace disque
management.health.diskspace.enabled=false

# Désactiver le check de la DB
management.health.db.enabled=false

3. Health Check Personnalisé​

Implémentation Simple​

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();
}
}
}

Résultat​

{
"status": "UP",
"components": {
"externalApi": {
"status": "UP",
"details": {
"api": "external-api",
"status": "reachable"
}
}
}
}

Health Check avec Seuils​

@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 Asynchrone​

Pour éviter de bloquer si le check est lent:

@Component
public class SlowServiceHealthIndicator implements HealthIndicator {

private final SlowService slowService;
private volatile Health cachedHealth = Health.unknown().build();

@Scheduled(fixedRate = 30000) // Toutes les 30 secondes
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; // Retourne immédiatement le cache
}
}

4. Groupes de Santé​

Configuration des Groupes​

# Groupe pour le load balancer (checks rapides)
management.endpoint.health.group.liveness.include=ping
management.endpoint.health.group.liveness.show-details=never

# Groupe pour Kubernetes readiness (checks complets)
management.endpoint.health.group.readiness.include=db,redis,externalApi
management.endpoint.health.group.readiness.show-details=when_authorized

# Groupe pour le monitoring (tout)
management.endpoint.health.group.full.include=*
management.endpoint.health.group.full.show-details=always

Accéder aux Groupes​

# Check de base
curl http://localhost:8080/actuator/health

# Groupe liveness
curl http://localhost:8080/actuator/health/liveness

# Groupe readiness
curl http://localhost:8080/actuator/health/readiness

# Groupe complet
curl http://localhost:8080/actuator/health/full

5. Kubernetes: Liveness vs Readiness​

Concepts​

Liveness Probe:
"L'application est-elle vivante?"
→ Si DOWN: Kubernetes redémarre le pod

Readiness Probe:
"L'application est-elle prête à recevoir du trafic?"
→ Si DOWN: Kubernetes retire le pod du load balancer

Configuration Spring Boot​

# Activer les probes Kubernetes
management.endpoint.health.probes.enabled=true

# Groupes automatiques créés:
# /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

Personnaliser les Groupes​

@Component
public class CustomLivenessIndicator implements HealthIndicator {

@Override
public Health health() {
// Vérification minimale: l'app répond
return Health.up().build();
}
}

@Component
public class CustomReadinessIndicator implements HealthIndicator {

private final DataSource dataSource;
private final RedisTemplate<?, ?> redis;

@Override
public Health health() {
// Vérifier que les dépendances sont prêtes
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 pour Load Balancer​

Endpoint Dédié Simple​

@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");
}

// Pour maintenance: mettre l'app hors service
@PostMapping("/admin/maintenance/enable")
public void enableMaintenance() {
healthy.set(false);
}

@PostMapping("/admin/maintenance/disable")
public void disableMaintenance() {
healthy.set(true);
}
}

7. Résumé​

Configuration Recommandée​

# Détails selon autorisation
management.endpoint.health.show-details=when_authorized
management.endpoint.health.show-components=when_authorized

# Activer les probes K8s
management.endpoint.health.probes.enabled=true

# Groupes personnalisés
management.endpoint.health.group.liveness.include=ping,livenessState
management.endpoint.health.group.readiness.include=readinessState,db,redis

Health Indicator Personnalisé​

@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();
}
}

Groupes Kubernetes​

GroupeUsageInclude
livenessPod alive?ping, basic checks
readinessReady for traffic?db, redis, external APIs

🎯 Prochaine Étape​

Place à la pratique! Configurons Actuator de A à Z.

➡️ TP11.1: Configuration Actuator


⬅️ Retour au Module 11