Spring Boot Actuator监控端点
约 1114 字大约 4 分钟
spring-bootactuator
2025-03-28
概述
Spring Boot Actuator 为生产环境应用提供了开箱即用的监控和管理能力。它通过一系列 HTTP 端点(Endpoints)暴露应用的健康状态、运行指标、环境配置等信息,并与 Micrometer 深度集成,支持将指标导出到 Prometheus、Grafana、Datadog 等监控系统。
快速开始
引入依赖后,Actuator 自动启用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency># application.yml
management:
endpoints:
web:
exposure:
include: health,info,metrics,env,beans,loggers
base-path: /actuator
endpoint:
health:
show-details: when_authorized端点架构
内置端点详解
1. Health —— 健康检查
/actuator/health 是最常用的端点,用于服务健康检查(如 K8s liveness/readiness probe)。
// 自定义健康指示器
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {
private final RestTemplate restTemplate;
public ExternalApiHealthIndicator(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public Health health() {
try {
ResponseEntity<String> response = restTemplate.getForEntity(
"https://api.example.com/health", String.class);
if (response.getStatusCode().is2xxSuccessful()) {
return Health.up()
.withDetail("api", "available")
.withDetail("responseTime", "120ms")
.build();
}
return Health.down()
.withDetail("api", "returned " + response.getStatusCode())
.build();
} catch (Exception e) {
return Health.down()
.withDetail("api", "unreachable")
.withException(e)
.build();
}
}
}配置分组健康检查(K8s 场景):
management:
endpoint:
health:
group:
liveness:
include: livenessState
readiness:
include: readinessState,db,redis访问路径:/actuator/health/liveness 和 /actuator/health/readiness。
2. Info —— 应用信息
# application.yml
info:
app:
name: My Application
version: 2.1.0
description: Order management service
team: Platform Engineering// 编程方式贡献信息
@Component
public class RuntimeInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("runtime", Map.of(
"java.version", System.getProperty("java.version"),
"processors", Runtime.getRuntime().availableProcessors(),
"maxMemory", Runtime.getRuntime().maxMemory() / 1024 / 1024 + "MB",
"uptime", ManagementFactory.getRuntimeMXBean().getUptime() + "ms"
));
}
}3. Metrics —— 运行指标
// 自定义指标
@Service
public class OrderService {
private final Counter orderCounter;
private final Timer orderProcessTimer;
private final AtomicInteger activeOrders;
public OrderService(MeterRegistry meterRegistry) {
this.orderCounter = Counter.builder("orders.created.total")
.description("Total number of orders created")
.tag("service", "order")
.register(meterRegistry);
this.orderProcessTimer = Timer.builder("orders.process.duration")
.description("Time to process an order")
.publishPercentiles(0.5, 0.95, 0.99)
.register(meterRegistry);
this.activeOrders = meterRegistry.gauge("orders.active",
new AtomicInteger(0));
}
public Order createOrder(OrderRequest request) {
activeOrders.incrementAndGet();
try {
return orderProcessTimer.record(() -> {
Order order = processOrder(request);
orderCounter.increment();
return order;
});
} finally {
activeOrders.decrementAndGet();
}
}
}访问指标数据:
# 查看所有可用指标
GET /actuator/metrics
# 查看具体指标
GET /actuator/metrics/jvm.memory.used
GET /actuator/metrics/orders.created.total
GET /actuator/metrics/http.server.requests?tag=uri:/api/orders&tag=status:2004. Env —— 环境配置
/actuator/env 展示所有配置属性来源及其值(敏感值自动脱敏):
management:
endpoint:
env:
show-values: when_authorized
# 自定义脱敏关键词
keys-to-sanitize: password,secret,key,token,credential安全配置
@Configuration
public class ActuatorSecurityConfig {
@Bean
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http)
throws Exception {
return http
.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
// health 和 info 允许匿名访问
.requestMatchers(EndpointRequest.to("health", "info"))
.permitAll()
// 其他端点需要 ACTUATOR 角色
.anyRequest().hasRole("ACTUATOR")
)
.httpBasic(Customizer.withDefaults())
.build();
}
}Prometheus 集成
引入 Prometheus 导出依赖:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>management:
endpoints:
web:
exposure:
include: health,info,prometheus
prometheus:
metrics:
export:
enabled: truePrometheus 配置文件 prometheus.yml:
scrape_configs:
- job_name: 'spring-boot-app'
metrics_path: '/actuator/prometheus'
scrape_interval: 15s
static_configs:
- targets: ['localhost:8080']自定义端点
@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {
private final Map<String, Boolean> features = new ConcurrentHashMap<>();
@ReadOperation
public Map<String, Boolean> getAllFeatures() {
return Collections.unmodifiableMap(features);
}
@ReadOperation
public Boolean getFeature(@Selector String featureName) {
return features.getOrDefault(featureName, false);
}
@WriteOperation
public void setFeature(@Selector String featureName, boolean enabled) {
features.put(featureName, enabled);
}
@DeleteOperation
public void deleteFeature(@Selector String featureName) {
features.remove(featureName);
}
}访问方式:
GET /actuator/features # 获取所有特性开关
GET /actuator/features/darkMode # 获取单个特性
POST /actuator/features/darkMode # 设置特性(请求体:{"enabled": true})
DELETE /actuator/features/darkMode # 删除特性动态日志级别调整
# 查看当前日志级别
GET /actuator/loggers/com.example.service
# 动态调整日志级别(无需重启)
POST /actuator/loggers/com.example.service
Content-Type: application/json
{
"configuredLevel": "DEBUG"
}
# 重置为默认级别
POST /actuator/loggers/com.example.service
Content-Type: application/json
{
"configuredLevel": null
}生产环境推荐配置
management:
server:
port: 9090 # 管理端口与业务端口分离
endpoints:
web:
exposure:
include: health,info,metrics,prometheus,loggers
base-path: /management
endpoint:
health:
show-details: when_authorized
probes:
enabled: true # 启用 K8s 探针
shutdown:
enabled: false # 禁用关闭端点
metrics:
tags:
application: ${spring.application.name}
environment: ${spring.profiles.active:default}总结
Spring Boot Actuator 提供了一套完整的生产级监控方案:Health 端点用于服务健康检查,Metrics 端点配合 Micrometer 收集运行指标,Prometheus 端点导出指标供监控系统采集。通过自定义 HealthIndicator、自定义指标和自定义端点,可以灵活扩展监控能力。生产环境中务必配置安全策略,避免敏感信息泄露。
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于