全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 8 分钟 ✍️ juanwangdev

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/prometheusPrometheus格式输出
/actuator/health健康状态检查

生产环境务必配置端点访问权限,避免敏感信息泄露。

要点总结

  • Counter用于累加计数,Gauge用于瞬时值
  • Timer记录耗时,自动计算百分位数
  • 通过MeterRegistry注册自定义指标
  • 配合Prometheus实现完整监控方案

📝 发现内容有误?点击此处直接编辑

← 上一篇 Spring Boot数据库连接池优化
下一篇 → Spring Boot缓存策略@Cacheable使用
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库