// 引入 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();
}
}
pom.xml 文件中引入 Prometheus 的 Java 客户端库,包括核心库、HotSpot 监控库和 HTTP 服务器库。CollectorRegistry 是 Prometheus 的核心组件之一,用于管理所有要暴露的指标。Gauge 是一种可以任意增减的度量类型,这里我们创建了一个名为 my_gauge 的 Gauge,并设置了它的帮助信息。gauge.set() 方法设置 Gauge 的值为 42.0。HTTPServer 类启动一个 HTTP 服务器,监听 8080 端口,并将 CollectorRegistry 注册到该服务器上,以便 Prometheus 可以抓取这些指标。Thread.currentThread().join() 来阻止主线程退出。这样,你就可以通过访问 http://localhost:8080/metrics 来查看 Prometheus 暴露的指标了。
上一篇:java归并排序
下一篇:java rsa解密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站