zoukankan      html  css  js  c++  java
  • 通过HttpServer向Prometheus暴露端点

    因为Prometheus是通过http接口的形式来采集数据的,所以需要向Prometheus server暴露端点。spring boot2.x版本在Actuator中集成了Prometheus,此外也可以手动向其暴露端点。接下来就说第二种。

    @Spi
    public interface MeterRegistryFactory {
        public MeterRegistry createMeterRegistry();
    }

    通过spi方式定义接口,方便使用其他时序数据库扩展。通过扩展点来加载Prometheus的实现:

                                                       

    @SpiMeta(name = "promMeterRegistryFactory")
    public class PrometheusMeterRegistryFactory implements MeterRegistryFactory {
        private static final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
    
        static {
            try {
                final int port = NumberUtils.toInt(System.getProperty("pepper.port"), 9146);
                //创建一个Http服务
                HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
                //服务设置一个针对/metrics路径请求的监听,并设置处理器HttpHandler
                server.createContext("/metrics", httpExchange -> {
                    //由PrometheusMeterRegistry抓取数据,它会将抓取的数据按Prometheus所需要的格式处理好
                    String response = prometheusRegistry.scrape();
                    //接下来有httpExchange将数据返回给Prometheus服务器
                    httpExchange.sendResponseHeaders(200, response.getBytes().length);
                    try (OutputStream os = httpExchange.getResponseBody()) {
                        os.write(response.getBytes());
                    }
                });
                //开启一个线程来处理Prometheus服务器抓取数据的请求
                new Thread(server::start).start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public MeterRegistry createMeterRegistry() {
            return prometheusRegistry;
        }
    }

     micrometer官网:https://micrometer.io/docs/registry/prometheus

    此外,再次安利一下同事开源的轻量级metrics收集框架:https://github.com/zrbcool/pepper-metrics

  • 相关阅读:
    spark基础(1)
    Homebrew的使用教程,镜像源的推荐,安装软件的方法
    Scala Trait(特征)
    P5308 [COCI2019] Quiz
    Vjudge contest 425291
    Vjudge contest 424925
    AT3558 Modern Painting
    Vjudge contest 425061
    Vjudge contest 423849
    Codeforces Round 704
  • 原文地址:https://www.cnblogs.com/jing-yi/p/14382302.html
Copyright © 2011-2022 走看看