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

  • 相关阅读:
    大厂面试高频Redis,记不住的多操作几次吧
    自动化测试系列之jenkins配置搭建环境
    关于linux服务器的磁盘监控的相关知识
    前端常见一些安全问题及解决方案
    如何使用PM2部署前端项目
    vuex状态管理器本地持久化
    关于在Vue中Typescript的写法
    websocket快速重连机制
    如何使用selenium打开多个浏览器
    运维人员踩坑记录之netplan遇坑,配置临时IP巧妙解决
  • 原文地址:https://www.cnblogs.com/jing-yi/p/14382302.html
Copyright © 2011-2022 走看看