Индикаторы состояния
Сообщайте о состоянии приложения и его зависимостей
«Индикаторы состояния» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The Health Endpoint
The /actuator/health endpoint reports whether the application and its dependencies are functioning. Load balancers and orchestrators poll it to decide if an instance should receive traffic.
GET /actuator/health
{ "status": "UP" }Aggregated Status
Overall health is an aggregate of many health indicators. If any critical indicator reports DOWN, the overall status becomes DOWN. Statuses include UP, DOWN, and OUT_OF_SERVICE.
Built-in Indicators
Boot auto-configures indicators for common dependencies — datasource, disk space, Redis, RabbitMQ, and others — whenever the corresponding starter is present. They contribute to the aggregate automatically.
Showing Health Details
By default details are hidden. Reveal per-component breakdowns with management.endpoint.health.show-details, ideally only to authenticated callers.
management:
endpoint:
health:
show-details: when-authorized
# or: always / neverDetailed Output
With details enabled, the response lists each component’s status and contributed data, making it easy to see which dependency is failing.
{
"status": "UP",
"components": {
"db": { "status": "UP", "details": { "database": "PostgreSQL" } },
"diskSpace": { "status": "UP" }
}
}A Custom HealthIndicator
Implement HealthIndicator to report on a dependency Boot does not cover — say, a downstream API. Return Health.up() or Health.down() with optional details.
@Component
public class PaymentApiHealthIndicator implements HealthIndicator {
private final PaymentClient client;
public PaymentApiHealthIndicator(PaymentClient client) { this.client = client; }
@Override
public Health health() {
return client.ping()
? Health.up().withDetail("latencyMs", client.lastLatency()).build()
: Health.down().withDetail("reason", "ping failed").build();
}
}Indicator Naming
The component name is derived from the bean/class name with the HealthIndicator suffix stripped. PaymentApiHealthIndicator appears as paymentApi in the output.
Liveness and Readiness Probes
In Kubernetes you distinguish liveness (is the app alive?) from readiness (can it serve traffic?). Boot exposes both as health groups when probes are enabled.
management:
endpoint:
health:
probes:
enabled: true
# exposes /actuator/health/liveness and /readinessHealth Groups
Group indicators under a named subset so probes only consider the relevant checks. Readiness might include the database; liveness usually should not, to avoid pod restarts on transient outages.
management:
endpoint:
health:
group:
readiness:
include: db,paymentApiTuning Status to HTTP Codes
Actuator maps health statuses to HTTP codes — UP to 200, DOWN to 503 by default — so infrastructure can act on the response code without parsing the body.
Designing Good Health Checks
Keep checks fast and meaningful:
- Probe real dependencies, not just process liveness
- Avoid heavy work that itself causes failures
- Separate liveness from readiness to prevent restart storms
Quick Check
Test your understanding of custom indicators.
Recap
Health endpoints signal operational status.
/actuator/healthaggregates many indicators- Built-in indicators cover common dependencies
- Implement
HealthIndicatorfor custom checks - Use
show-detailswisely; names strip the suffix - Enable liveness/readiness probes and groups for Kubernetes
Часто задаваемые вопросы
Урок «Индикаторы состояния» бесплатный?
Да — полный текст урока «Индикаторы состояния» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Чему я научусь в уроке «Индикаторы состояния»?
Сообщайте о состоянии приложения и его зависимостей Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?
Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Индикаторы состояния»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?
Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Включение конечных точек Actuator
- Индикаторы состояния
- Пользовательские метрики с Micrometer
- Защита конечных точек Actuator