前言

目前翻阅了网上的各种代码集成Prometheus的demo,千篇一律,基本都是复制粘贴,均是1.x版本的springboot且代码都是跑不通的。现根据开源依赖debug源码,实践出可用版本。
完整代码地址 gitee-yonyong/my-prometheus
此代码亲测可用。

版本

io.micrometer 1.2.1
springboot 2.0.5.RELEASE

本代码实现功能

1.Java接入Prometheus,提供JVM监控及自定义指标监控
2.实现自定义指标的接入功能
3.实现指标label动态赋值功能

代码片段

build.gradle

    compile "io.prometheus:simpleclient_hotspot:0.0.24"
    compile "io.micrometer:micrometer-registry-prometheus:1.2.1"
    compile "io.micrometer:micrometer-core:1.2.1"

注册MeterRegistry

 @Bean(value = "meterRegistryCustomizer")
    MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer() {
        return meterRegistry -> meterRegistry.config()
                .commonTags("application", "springboot-app");
    }

MyMetrics 自定义指标


    /**
     * 计数器可以用于记录只会增加不会减少的指标类型,比如记录应用请求的总量(http_requests_total),
     * cpu使用时间(process_cpu_seconds_total)等。 一般而言,Counter类型的metrics指标在命名中
     * 我们使用_total结束。
     */
    public static Counter requestCounter = Counter.build()
            .name("io_namespace_http_requests_total")
            .labelNames("path", "method", "code")
            .help("Total requests.").register();

注册自定义指标

@Component
public class InitPrometheus implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    PrometheusMeterRegistry meterRegistry;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        new MyMetrics();

        CollectorRegistry prometheusRegistry = meterRegistry.getPrometheusRegistry();

        prometheusRegistry.register(MyMetrics.requestCounter);
        prometheusRegistry.register(MyMetrics.inprogressRequests);
        prometheusRegistry.register(MyMetrics.requestLatencyHistogram);
        prometheusRegistry.register(MyMetrics.requestLatency);
    }
}

使用

配置拦截器

@Configuration
public class AppConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new PrometheusMetricsInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

拦截器为指标赋值

public class PrometheusMetricsInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();

        MyMetrics.inprogressRequests.labels(requestURI,method).inc();

        MyMetrics.histogramRequestTimer = MyMetrics.requestLatencyHistogram.labels(requestURI, method, String.valueOf(status)).startTimer();

        MyMetrics.requestTimer = MyMetrics.requestLatency.labels(requestURI, method, String.valueOf(status)).startTimer();
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();

        MyMetrics.requestCounter.labels(requestURI, method, String.valueOf(status)).inc();

        MyMetrics.inprogressRequests.labels(requestURI,method).dec();

        MyMetrics.histogramRequestTimer.observeDuration();

        MyMetrics.requestTimer.observeDuration();

        super.afterCompletion(request, response, handler, ex);
    }
}

启动项目,查看服务指标信息

http://localhost:8502/metrics/prometheus
posted on 2020-11-21 10:01  yonyong  阅读(5942)  评论(0编辑  收藏  举报