Spring Boot Actuator — это модуль в экосистеме Spring Boot, который предоставляет готовые endpoints (конечные точки) для мониторинга, управления и диагностики вашего приложения. Он позволяет разработчикам и администраторам получать информацию о состоянии приложения, его производительности, метриках, логах и других аспектах в реальном времени.
Actuator предоставляет набор встроенных endpoints, которые можно использовать для получения информации о приложении. Некоторые из них:
Для использования Actuator необходимо добавить зависимость в pom.xml
(для Maven) или build.gradle
(для Gradle).
Пример для Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Пример для Gradle:
implementation 'org.springframework.boot:spring-boot-starter-actuator'
После добавления зависимости Actuator автоматически активируется, и его endpoints становятся доступными.
Рассмотрим пример приложения с активированным Actuator:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
После запуска приложения вы можете получить доступ к endpoints Actuator через HTTP. Например:
http://localhost:8080/actuator/health
http://localhost:8080/actuator/metrics
http://localhost:8080/actuator/info
По умолчанию не все endpoints Actuator включены. Вы можете настроить, какие endpoints будут доступны, в файле application.properties
или application.yml
.
Пример настройки в application.properties
:
# Включить все endpoints
management.endpoints.web.exposure.include=*
# Отключить определенные endpoints
management.endpoints.web.exposure.exclude=env,beans
Пример настройки в application.yml
:
management:
endpoints:
web:
exposure:
include: "*"
exclude: env,beans
Вы можете кастомизировать существующие endpoints или создавать свои собственные. Например, можно добавить кастомную информацию в /health
или /info
.
Пример кастомизации /health
:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// Логика проверки здоровья
boolean isHealthy = checkHealth();
if (isHealthy) {
return Health.up().withDetail("CustomHealth", "Everything is OK!").build();
} else {
return Health.down().withDetail("CustomHealth", "Something is wrong!").build();
}
}
private boolean checkHealth() {
// Логика проверки
return true;
}
}
Endpoints Actuator могут содержать чувствительную информацию, поэтому важно обеспечить их защиту. Вы можете использовать Spring Security для ограничения доступа.
Пример настройки безопасности:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().permitAll()
)
.httpBasic();
return http.build();
}
Использование Spring Boot Actuator значительно упрощает процесс мониторинга и управления приложением, что особенно важно в production-среде.