首页 > 其他分享 >Springboot自定义Prometheus采集指标

Springboot自定义Prometheus采集指标

时间:2024-09-29 16:01:37浏览次数:16  
标签:sysName Springboot 自定义 micrometer 指标 Prometheus io import

添加依赖

<!--增加Prometheus依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

项目配置

配置application.yml文件

spring:
    application:
        name: my-metrics

server:
    port: 8080
    tomcat:
      mbeanregistry:
          enabled: true #启用Tomcat MBean注册表,以便于通过JMX进行监控和管理

management:
    endpoints:
        web:
            exposure:
                include: "*" #将所有Actuator端点暴露
    prometheus:
        metrics:
            export:
                enabled: true #启用Prometheus指标导出
    metrics:
        tags:
            application: ${spring.application.name}

自定义指标

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import jakarta.servlet.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * @Description 使用过滤器添加自定义指标
 **/
@Component
public class MyMetricsFilter implements Filter {

    @Autowired
    private MeterRegistry registry;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //自定义指标方法
        addMetrics();
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 添加自定义指标
     */
    public void addMetrics() {
        List<String> sysNames = new ArrayList<>();
        sysNames.add("sys1");
        sysNames.add("sys2");

        sysNames.forEach(sysName -> {
            Gauge.builder("my.metrics.monitor", getValue(sysName)) // getValue(sysName)返回一个Supplier<Number>对象, 对象值为匿名函数, 匿名函数会在创建指标时调用,返回自定义指标的值
                    .tags(Tags.of("service", sysName)) // 指标标签
                    .description("my metrics monitor") // 指标描述
                    .register(registry); // 注册到MeterRegistry
        });
    }

    public Supplier<Number> getValue(String sysName) {
        return () -> {
            // 在这里使用 sysName 参数, 编写自定义指标的逻辑
            System.out.println("System name: " + sysName);
            return sysName.hashCode();
        };
    }
}

获取自定义指标

启动项目,访问http://localhost:8080/actuator/prometheus,即可获取自定义指标
image

标签:sysName,Springboot,自定义,micrometer,指标,Prometheus,io,import
From: https://www.cnblogs.com/zjh/p/18440208

相关文章