Spring Boot监控指标体系
Spring Boot Actuator 集成 Micrometer,提供标准化监控指标体系。
核心依赖
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
指标类型
| 类型 | 用途 | 场景 |
|---|---|---|
| Counter | 只增计数 | 请求次数、错误次数 |
| Gauge | 可增可减 | 当前连接数、队列长度 |
| Timer | 耗时统计 | 接口响应时间 |
| DistributionSummary | 分布统计 | 请求体大小分布 |
配置端点
YAML
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: always
metrics:
tags:
application: ${spring.application.name}
自定义指标
Java
@Component
public class CustomMetrics {
private final Counter requestCounter;
private final Gauge activeConnections;
public CustomMetrics(MeterRegistry registry) {
this.requestCounter = Counter.builder("api.requests")
.description("API请求总数")
.tag("type", "http")
.register(registry);
registry.gauge("active.connections",
Collections.emptyList(),
connectionPool,
pool -> pool.getActiveCount());
}
public void incrementRequest() {
requestCounter.increment();
}
}
Timer使用示例
Java
@Service
public class OrderService {
private final Timer orderTimer;
public OrderService(MeterRegistry registry) {
this.orderTimer = Timer.builder("order.process.time")
.description("订单处理耗时")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
}
public void processOrder(Order order) {
orderTimer.record(() -> doProcess(order));
}
}
常用端点
| 端点 | 说明 |
|---|---|
| /actuator/metrics | 查看所有指标名称 |
| /actuator/metrics/{name} | 查看指定指标详情 |
| /actuator/prometheus | Prometheus格式输出 |
| /actuator/health | 健康状态检查 |
生产环境务必配置端点访问权限,避免敏感信息泄露。
要点总结
- Counter用于累加计数,Gauge用于瞬时值
- Timer记录耗时,自动计算百分位数
- 通过MeterRegistry注册自定义指标
- 配合Prometheus实现完整监控方案
📝 发现内容有误?点击此处直接编辑