Spring Boot Actuator 是 Spring Boot 框架中用于监控和管理应用程序的核心模块。它为生产环境提供了开箱即用的功能,帮助开发者深入了解应用程序的运行时状态。
核心价值:提供健康检查、指标收集、配置查看和操作控制能力。
技术架构:基于 Micrometer 门面库,支持与 Prometheus、Graphite 等多种监控系统无缝集成。
快速集成
集成 Actuator 非常简单,只需添加依赖并进行基础配置。
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>基础配置
management:
endpoints:
web:
exposure:
include: "*" # 暴露所有端点(生产环境慎用)
endpoint:
health:
show-details: always # 显示健康检查详细信息Actuator 通过一系列端点暴露应用信息,以下是核心端点的功能说明。
端点路径:/actuator/health
功能描述:验证应用及其依赖(如数据库、消息队列)的运行状态。默认返回 {"status": "UP"},配置 show-details: always 后可查看组件详细信息。
端点路径:/actuator/info
功能描述:显示应用的自定义信息,如版本号、构建时间等。可通过配置文件添加 info.app.name 等属性。
端点路径:/actuator/metrics
功能描述:提供 JVM 内存、CPU 使用率、HTTP 请求统计等性能指标数据。
端点路径:/actuator/env
功能描述:展示所有环境变量和配置属性,自动过滤敏感信息(如密码)。
beans:显示所有 Spring Bean。
threaddump:生成线程堆栈,用于分析死锁。
mappings:显示所有 @RequestMapping 路径。
通过实现 HealthIndicator 接口,可以添加自定义的健康检查逻辑。
代码示例:
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean isHealthy = checkService();
if (isHealthy) {
return Health.up().withDetail("customService", "Available").build();
} else {
return Health.down().withDetail("customService", "Unavailable").build();
}
}
}使用 @Endpoint 注解可以定义全新的监控端点。
代码示例:
@Endpoint(id = "systemtime")
public class SystemTimeEndpoint {
@ReadOperation
public Map<String, Object> getTime() {
return Map.of("timestamp", System.currentTimeMillis(), "format", "UNIX时间戳");
}
}通过添加 micrometer-registry-prometheus 依赖,可轻松集成 Prometheus 监控系统。
配置示例:
management:
endpoints:
web:
exposure:
include: health,info,prometheus最小化暴露:仅暴露必要的端点,如 health 和 info。
路径定制:修改默认的 /actuator 前缀,增强安全性。
结合 Spring Security,对端点访问进行权限控制。
安全配置示例:
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasRole("ACTUATOR_ADMIN")
.and().httpBasic();
}
}避免暴露敏感端点(如 env、threaddump)到公网。
定期检查和更新 Actuator 配置,确保安全性。