一、Actuator
Spring Boot Actuator 是 Spring Boot 提供的一个生产就绪(Production-Ready)功能模块,用于监控和管理 Spring Boot 应用程序。它通过 HTTP 端点或 JMX 暴露了一系列操作,让运维人员能够实时监控应用状态、收集指标、了解配置信息等。
二、核心功能概览
Spring Boot Actuator包括了健康检查、指标监控、应用信息、环境信息、日志管理、审计事件、
数据库连接、磁盘空间、第三方服务、JVM 指标、HTTP 请求、自定义指标
三、快速开始
1. 添加依赖
<!– pom.xml –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!– 如需 Web 端点,还需添加 –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 基本配置
# application.yml
management:
endpoints:
web:
exposure:
include: "*" # 暴露所有端点(生产环境需谨慎)
base-path: /actuator # 端点基础路径
endpoint:
health:
show-details: always # 显示健康检查详情
metrics:
enabled: true
info:
enabled: true
# 自定义端口(与主应用端口分离)
server:
port: 9090
四、核心端点详解
1. 健康检查端点 – /actuator/health
# 健康检查配置
management:
endpoint:
health:
show-details: always # always, when_authorized, never
show-components: always
probes:
enabled: true # Kubernetes 就绪/存活探针支持
// 自定义健康检查指示器
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean isServiceUp = checkService();
if (isServiceUp) {
return Health.up()
.withDetail("service", "Available")
.withDetail("responseTime", "50ms")
.build();
} else {
return Health.down()
.withDetail("service", "Unavailable")
.withDetail("error", "Connection timeout")
.build();
}
}
private boolean checkService() {
// 检查第三方服务或组件
return true;
}
}
// 内置健康指示器
@Configuration
public class HealthConfig {
@Bean
public HealthIndicator dbHealthIndicator(DataSource dataSource) {
return new DataSourceHealthIndicator(dataSource);
}
}
健康状态示例:
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 500068036608,
"free": 365218222080,
"threshold": 10485760,
"exists": true
}
},
"ping": {
"status": "UP"
},
"customService": {
"status": "UP",
"details": {
"service": "Available",
"responseTime": "50ms"
}
}
}
}
2. 指标端点 – /actuator/metrics
// 使用 Micrometer 收集指标
@Component
public class OrderService {
private final MeterRegistry meterRegistry;
private final Counter orderCounter;
private final Timer orderProcessingTimer;
public OrderService(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
// 创建计数器
this.orderCounter = Counter.builder("orders.count")
.description("Total number of orders")
.tag("service", "order")
.register(meterRegistry);
// 创建计时器
this.orderProcessingTimer = Timer.builder("orders.processing.time")
.description("Order processing time")
.register(meterRegistry);
}
public Order createOrder(OrderRequest request) {
// 开始计时
Timer.Sample sample = Timer.start(meterRegistry);
try {
// 业务逻辑…
Order order = processOrder(request);
// 增加计数器
orderCounter.increment();
return order;
} finally {
// 停止计时并记录
sample.stop(orderProcessingTimer);
}
}
// 使用计量器
public void trackActiveUsers() {
Gauge.builder("users.active", () -> getActiveUserCount())
.description("Number of active users")
.register(meterRegistry);
}
}
// 查看特定指标
// GET /actuator/metrics/orders.count
// GET /actuator/metrics/jvm.memory.used
3. 环境信息端点 – /actuator/env
// 动态修改配置(需要 refresh 端点)
@Configuration
@RefreshScope // 支持配置热更新
public class AppConfig {
@Value("${app.feature.enabled:false}")
private boolean featureEnabled;
// 当配置更新后,Bean会被重新创建
}
4. 信息端点 – /actuator/info
# 静态信息配置
info:
app:
name: "订单服务"
version: "2.1.0"
description: "处理用户订单"
team:
name: "电商团队"
contact: "team@example.com"
build:
artifact: "${project.artifactId}"
version: "${project.version}"
time: "${build.time}"
# 从 Git 获取信息
management:
info:
git:
mode: full # 显示完整git信息
// 动态信息提供器
@Component
public class CustomInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
Map<String, Object> details = new HashMap<>();
details.put("uptime", getUptime());
details.put("region", "us-east-1");
details.put("instance-id", "i-1234567890");
builder.withDetail("runtime", details);
}
private String getUptime() {
// 计算应用运行时间
return "5 days 3 hours";
}
}
5. 其他重要端点
| beans | /actuator/beans | 显示所有 Spring Bean |
| mappings | /actuator/mappings | 显示所有 @RequestMapping 路径 |
| loggers | /actuator/loggers | 查看和修改日志级别 |
| threaddump | /actuator/threaddump | 获取线程快照 |
| heapdump | /actuator/heapdump | 下载堆转储文件 |
| prometheus | /actuator/prometheus | Prometheus 格式的指标 |
五、安全配置
1. Spring Security 集成
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests()
// 健康端点公开访问
.requestMatchers(EndpointRequest.to("health", "info"))
.permitAll()
// 其他端点需要认证
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic(); // 使用基本认证
// 或者使用 JWT 等认证方式
}
}
// 或使用简单的配置
@Configuration
public class SimpleSecurityConfig {
@Bean
public SecurityFilterChain actuatorFilterChain(HttpSecurity http) throws Exception {
http
.antMatcher("/actuator/**")
.authorizeRequests()
.antMatchers("/actuator/health/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
}
2. 敏感端点保护
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
# 自定义路径
base-path: /management
path-mapping:
health: healthcheck
shutdown: stop # 重命名敏感端点
endpoint:
shutdown:
enabled: false # 生产环境禁用 shutdown 端点
heapdump:
enabled: true
sensitive: true # 标记为敏感
六、与监控系统集成
1. Prometheus + Grafana
# 启用 Prometheus 端点
management:
endpoints:
web:
exposure:
include: health,prometheus,metrics
metrics:
export:
prometheus:
enabled: true
tags:
application: ${spring.application.name}
environment: ${ENV:dev}
# Prometheus 配置示例
# prometheus.yml
scrape_configs:
– job_name: 'spring-boot'
metrics_path: '/actuator/prometheus'
static_configs:
– targets: ['localhost:8080']
labels:
application: 'order-service'
2. ELK 集成(日志收集)
logging:
file:
name: logs/app.log
logback:
rollingpolicy:
max-file-size: 10MB
max-history: 30
management:
endpoints:
web:
exposure:
include: loggers
endpoint:
loggers:
enabled: true
# 动态修改日志级别
# POST /actuator/loggers/com.example
# {
# "configuredLevel": "DEBUG"
# }
七、高级特性
1. 自定义端点
@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public Map<String, Object> getInfo() {
Map<String, Object> info = new HashMap<>();
info.put("timestamp", Instant.now().toString());
info.put("status", "OK");
info.put("activeUsers", getActiveUserCount());
return info;
}
@WriteOperation
public String executeOperation(@Selector String operation) {
return "Executed: " + operation;
}
@DeleteOperation
public String clearCache() {
return "Cache cleared";
}
}
2. 健康检查分组
management:
endpoint:
health:
show-details: when_authorized
group:
readiness:
include: db,diskSpace,customService
liveness:
include: ping
external:
include: redis,externalApi
probes:
enabled: true # 为 Kubernetes 准备
# 单独暴露分组端点
health:
liveness-state:
enabled: true
readiness-state:
enabled: true
3. Micrometer 指标定制
@Configuration
public class MetricsConfig {
@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config()
.commonTags(
"application", "order-service",
"region", System.getenv("REGION"),
"instance", System.getenv("HOSTNAME")
);
}
@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
// 自动为 @Timed 注解的方法收集指标
return new TimedAspect(registry);
}
}
@Service
public class ProductService {
@Timed(value = "product.search.time",
description = "Time taken to search products")
public List<Product> searchProducts(String keyword) {
// 业务逻辑
return productRepository.search(keyword);
}
}
八、生产环境最佳实践
1. 安全配置清单
# production-actuator.yml
management:
endpoints:
web:
exposure:
# 生产环境只暴露必要的端点
include: health,info,prometheus
base-path: /internal # 使用非常规路径
path-mapping:
health: status # 重命名端点
server:
port: 9091 # 使用独立端口
address: 127.0.0.1 # 只允许本地访问
endpoint:
shutdown:
enabled: false # 禁用危险端点
heapdump:
enabled: false
env:
enabled: false # 避免暴露配置
beans:
enabled: false
2. 健康检查配置
management:
health:
db:
enabled: true
redis:
enabled: true
mail:
enabled: true
diskspace:
threshold: 10MB
endpoint:
health:
show-details: when_authorized
show-components: never
status:
order: DOWN, OUT_OF_SERVICE, UP, UNKNOWN
九、Actuator 端点总览表
| auditevents | 审计事件 | 是 | 是 |
| beans | Spring Beans | 是 | 是 |
| caches | 缓存信息 | 是 | 是 |
| conditions | 自动配置条件 | 是 | 是 |
| configprops | 配置属性 | 是 | 是 |
| env | 环境变量 | 是 | 是 |
| flyway | Flyway 迁移 | 是 | 是 |
| health | 健康状态 | 否 | 是 |
| heapdump | 堆转储 | 是 | 是 |
| httptrace | HTTP 跟踪 | 是 | 是 |
| info | 应用信息 | 否 | 是 |
| integrationgraph | 集成图 | 是 | 是 |
| loggers | 日志配置 | 是 | 是 |
| liquibase | Liquibase 迁移 | 是 | 是 |
| metrics | 应用指标 | 是 | 是 |
| mappings | URL 映射 | 是 | 是 |
| prometheus | Prometheus 指标 | 是 | 是 |
| scheduledtasks | 计划任务 | 是 | 是 |
| sessions | HTTP 会话 | 是 | 是 |
| shutdown | 关闭应用 | 是 | 否 |
| threaddump | 线程转储 | 是 | 是 |
总结
Spring Boot Actuator 主要作用:
监控应用健康:实时了解应用运行状态
收集运行指标:为性能分析和容量规划提供数据
管理应用配置:动态调整运行参数
生产就绪功能:提供生产环境所需的各种管理功能
集成监控系统:与 Prometheus、Grafana 等无缝集成
Actuator 是 Spring Boot 微服务架构中不可或缺的运维工具,它极大简化了应用监控和管理的复杂度,是构建可观测性系统的核心组件。



