middle
Как реализовать health checks и мониторинг микросервисов?
Health checks и мониторинг — критические аспекты production-ready микросервисов. Spring Boot Actuator предоставляет готовые эндпоинты для проверки здоровья, а Prometheus + Grafana — для сбора и визуализации метрик.
Spring Boot Actuator: конфигурация и кастомный HealthIndicator
# application.yml
management:
endpoints:
web:
exposure:
include: health, info, metrics, prometheus
endpoint:
health:
show-details: when-authorized
show-components: always
health:
db:
enabled: true
diskspace:
enabled: true
kafka:
enabled: true
@Component
public class PaymentGatewayHealthIndicator implements HealthIndicator {
private final PaymentGatewayClient gatewayClient;
@Override
public Health health() {
try {
boolean isAvailable = gatewayClient.ping();
if (isAvailable) {
return Health.up()
.withDetail("gateway", "Payment Gateway доступен")
.withDetail("responseTime", "45ms")
.build();
} else {
return Health.down()
.withDetail("gateway", "Payment Gateway не отвечает")
.build();
}
} catch (Exception e) {
return Health.down(e)
.withDetail("error", e.getMessage())
.build();
}
}
}
Liveness и Readiness Probes (для Kubernetes)
Пример
management:
endpoint:
health:
probes:
enabled: true
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
/actuator/health/liveness— жив ли сервис (если нет — Kubernetes перезапустит контейнер)./actuator/health/readiness— готов ли сервис принимать трафик (если нет — Kubernetes перестанет направлять трафик).
Пример
# Kubernetes deployment
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 20
periodSeconds: 5
Prometheus + Grafana: кастомные метрики
@Service
public class PaymentService {
private final Counter paymentCounter;
private final Timer paymentTimer;
public PaymentService(MeterRegistry registry) {
this.paymentCounter = Counter.builder("payments.processed")
.description("Количество обработанных платежей")
.tag("service", "payment-service")
.register(registry);
this.paymentTimer = Timer.builder("payments.duration")
.description("Время обработки платежа")
.register(registry);
}
public void processPayment(PaymentRequest request) {
paymentTimer.record(() -> {
doProcess(request);
paymentCounter.increment();
});
}
}
Endpoint /actuator/prometheus предоставляет метрики в формате Prometheus:
# HELP payments_processed_total Количество обработанных платежей
payments_processed_total{service="payment-service"} 1542.0
# HELP payments_duration_seconds Время обработки платежа
payments_duration_seconds_sum{service="payment-service"} 125.4
Ключевые метрики для мониторинга (RED-метрики)
| Метрика | Описание |
|---|---|
| Rate | Количество запросов в секунду |
| Errors | Процент ошибок |
| Duration | Время ответа (p50, p95, p99) |
На собеседовании: различайте liveness и readiness probes — это частый вопрос. Liveness: «жив ли процесс» (перезапуск при false), readiness: «готов ли принимать трафик» (отключение от балансировщика при false). Упомяните RED-метрики как стандарт мониторинга.