极核getshell 2025-12-04 12:28 采纳率: 31.8%
浏览 4

Spring Boot Actuator的/metrics端点如何通过Micrometer收集和暴露应用指标? 如何自定义指标并集成到Prometheus中?

Spring Boot Actuator的/metrics端点如何通过Micrometer收集和暴露应用指标? 如何自定义指标并集成到Prometheus中?

  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-12-04 13:08
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    Spring Boot Actuator与Micrometer集成指南

    概述

    Spring Boot Actuator提供了一个/metrics端点来暴露应用的性能指标。Micrometer是一个用于收集和暴露应用指标的库,可以与Spring Boot Actuator集成。下面我们将介绍如何通过Micrometer收集和暴露应用指标,并自定义指标并集成到Prometheus中。

    依赖配置

    在pom.xml文件中添加以下依赖:

    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-core</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
    

    配置Micrometer

    在application.properties或application.yml文件中添加以下配置:

    management.metrics.export.prometheus.enabled=true
    management.metrics.export.prometheus.config.file=classpath:prometheus.yml
    

    自定义指标

    创建一个自定义指标类,例如CustomGauge.java:

    import io.micrometer.core.instrument.Counter;
    import io.micrometer.core.instrument.Gauge;
    import io.micrometer.core.instrument.MeterRegistry;
    import org.springframework.stereotype.Component;
    
    @Component
    public class CustomGauge {
    
        private final Gauge gauge;
    
        public CustomGauge(MeterRegistry registry) {
            gauge = registry.gauge("custom.gauge", () -> 0);
        }
    
        public void increment() {
            gauge.increment();
        }
    }
    

    集成到Prometheus

    在prometheus.yml文件中添加以下配置:

    global:
      scrape_interval: 10s
    
    scrape_configs:
      - job_name: 'spring-boot'
        metrics_path: '/actuator/metrics'
        static_configs:
          - targets: ['localhost:8080']
    

    启动应用

    启动Spring Boot应用,访问http://localhost:8080/actuator/metrics可以看到自定义指标。

    总结

    通过Micrometer收集和暴露应用指标,并自定义指标并集成到Prometheus中,需要配置Micrometer依赖,配置Micrometer,创建自定义指标类,集成到Prometheus中。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月4日