Actuator:端点、健康检查与指标暴露
应用上线后要能"体检":进程是否活着、依赖是否可用、内存和连接池用了多少。Spring Boot Actuator 把这些能力做成一个个 HTTP/JMX 端点,是生产运维与容器探针的基础。以下示例基于 Boot 3.x。
引入与默认行为
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
启动后访问 /actuator 会列出可用端点。Boot 3 默认只在 Web 上暴露 health 端点(Boot 2 时代默认暴露的 info 等已不再默认开放),需要显式放行:
management:
endpoints:
web:
exposure:
include: health,info,metrics,env # 生产慎用 *;env/beans 等含敏感信息
endpoint:
health:
show-details: always # 默认 only-when-authorized,改为总是显示明细
健康检查与探针
GET /actuator/health 返回总体状态 UP/DOWN,并汇总各 HealthIndicator(磁盘、DB、Redis、消息队列等)。自定义健康项只需实现接口并交给 Spring:
@Component
public class DiskHealthIndicator implements HealthIndicator {
@Override
public Health health() {
long free = new File("/").getFreeSpace(); // 示例:磁盘剩余字节
if (free < 1_000_000_000L) {
return Health.down().withDetail("freeBytes", free).build();
}
return Health.up().withDetail("freeBytes", free).build();
}
}
// 输出:/actuator/health 中出现 "disk": {"status":"UP","freeBytes":...}
K8s/Docker 探针常分存活与就绪两组(第 39 章配合使用):
management:
endpoint:
health:
probes:
enabled: true # 开放 /actuator/health/liveness 与 /actuator/health/readiness
liveness 表示进程该不该被重启,readiness 表示能不能接流量;优雅停机期间 readiness 会自动转 DOWN,先把流量摘走再退出。
指标暴露
加依赖 micrometer-registry-prometheus(见第 40 章)后会出现 /actuator/prometheus,Prometheus 从这里拉取 JVM、HTTP、HikariCP 等指标。默认不暴露该端点,需把它加进 include。其他常用端点:/actuator/info(构建与自定义信息)、/actuator/metrics、/actuator/env(环境变量,敏感)、/actuator/heapdump、/actuator/shutdown(POST 且默认禁用)。
安全提醒
- Actuator 端点不要直接裸露到公网:用 Spring Security 限制(第 29~33 章),或拆到独立管理端口
management.server.port; - env、beans、configprops 会泄露配置细节,按最小暴露原则配置;
- 健康检查本身要轻量,别在 HealthIndicator 里做重查询或外部调用超时。
小结:Actuator 通过 health 提供存活与就绪判断、通过 info/metrics/env 提供观测入口;记得显式配置暴露范围并做好访问控制。