Java 中的 Prometheus 指标:simpleclient 库
Prometheus 是一个强大的开源监控和告警系统,它从各种来源收集指标。对于 Java 应用程序,有多个库可用于与 Prometheus 集成。最主要且最流行的是来自 Prometheus 项目本身的 simpleclient。它提供了一种极简、线程安全且高性能的方式来创建、注册和导出指标。
什么是 simpleclient?
simpleclient 是 Prometheus 的官方 Java 库,允许开发者以最小的开销向应用程序添加指标。它支持四种主要的指标类型:
- Counter — 只增不减的计数器(例如,请求数量)。
- Gauge — 可增可减的值(例如,活跃连接数、温度)。
- Histogram — 测量值分布情况的直方图(例如,请求执行时间)。
- Summary — 与直方图类似的摘要,但在客户端计算分位数。
安装与配置
要使用 simpleclient,请在 pom.xml(Maven)中添加以下依赖:
<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_servlet</artifactId> <version>0.16.0</version></dependency>对于 Gradle:
implementation 'io.prometheus:simpleclient:0.16.0'implementation 'io.prometheus:simpleclient_hotspot:0.16.0'implementation 'io.prometheus:simpleclient_servlet:0.16.0'创建和注册指标
我们来看一个简单的请求计数器的创建。指标注册在全局注册表 CollectorRegistry.defaultRegistry 中。
import io.prometheus.client.Counter;import io.prometheus.client.Gauge;
public class MetricsExample { // 创建一个名为 "http_requests_total" 的计数器,带有标签 "method" 和 "endpoint" static final Counter requests = Counter.build() .name("http_requests_total") .help("Total number of HTTP requests.") .labelNames("method", "endpoint") .register();
// 创建一个用于活跃会话数量的仪表 static final Gauge activeSessions = Gauge.build() .name("active_sessions") .help("Current number of active sessions.") .register();
public static void processRequest(String method, String endpoint) { // 增加计数器 requests.labels(method, endpoint).inc(); // 设置仪表的值(例如,队列大小) activeSessions.set(42); }}通过 HTTP 导出指标
为了让 Prometheus 能够收集指标,需要提供一个 /metrics 端点。最简单的方法是使用内置的 Servlet。如果您使用 Spring Boot,请添加 simpleclient_spring_boot 依赖。
import io.prometheus.client.exporter.MetricsServlet;import io.prometheus.client.hotspot.DefaultExports;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;
@WebServlet("/metrics"