Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java prometheus

作者:苏染瞳°   发布日期:2025-05-17   浏览:34

// 引入 Prometheus 的 Java 客户端库
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient</artifactId>
    <version>0.16.0</version>
</dependency>
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_hotspot</artifactId>
    <version>0.16.0</version>
</dependency>
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_httpserver</artifactId>
    <version>0.16.0</version>
</dependency>

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.HTTPServer;

public class PrometheusExample {

    public static void main(String[] args) throws Exception {
        // 创建一个新的 CollectorRegistry 实例
        CollectorRegistry collectorRegistry = new CollectorRegistry();

        // 创建一个 Gauge 指标,并将其注册到 CollectorRegistry 中
        Gauge gauge = Gauge.build()
                .name("my_gauge")
                .help("This is a sample gauge metric.")
                .register(collectorRegistry);

        // 设置 Gauge 的值
        gauge.set(42.0);

        // 启动 HTTP 服务器,监听 8080 端口,并暴露 Prometheus 指标
        HTTPServer server = new HTTPServer(8080, collectorRegistry, true);
        System.out.println("Prometheus metrics are available at http://localhost:8080/metrics");

        // 让程序保持运行,以便 Prometheus 可以抓取指标
        Thread.currentThread().join();
    }
}

解释说明:

  1. 引入依赖:首先需要在 pom.xml 文件中引入 Prometheus 的 Java 客户端库,包括核心库、HotSpot 监控库和 HTTP 服务器库。
  2. 创建 CollectorRegistryCollectorRegistry 是 Prometheus 的核心组件之一,用于管理所有要暴露的指标。
  3. 创建 Gauge 指标Gauge 是一种可以任意增减的度量类型,这里我们创建了一个名为 my_gauge 的 Gauge,并设置了它的帮助信息。
  4. 设置 Gauge 的值:通过 gauge.set() 方法设置 Gauge 的值为 42.0。
  5. 启动 HTTP 服务器:使用 HTTPServer 类启动一个 HTTP 服务器,监听 8080 端口,并将 CollectorRegistry 注册到该服务器上,以便 Prometheus 可以抓取这些指标。
  6. 保持程序运行:为了让 Prometheus 能够持续抓取指标,程序需要保持运行状态。这里使用 Thread.currentThread().join() 来阻止主线程退出。

这样,你就可以通过访问 http://localhost:8080/metrics 来查看 Prometheus 暴露的指标了。

上一篇:java归并排序

下一篇:java rsa解密

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站