使用JAX-RS的Java应用如何不引入Spring添加Prometheus指标端点
完全可以通过自定义javax.ws.rs端点的方式暴露Prometheus指标,不需要引入Spring组件,也不需要单独启动额外端口的HTTPServer,实现方案如下:
实现步骤
1. 引入必要依赖
仅需要引入Prometheus官方Java客户端核心依赖,无需任何Spring相关组件:
<!-- Prometheus核心客户端 --> <dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient</artifactId> <version>0.16.0</version> </dependency> <!-- Prometheus指标格式化工具 --> <dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient_common</artifactId> <version>0.16.0</version> </dependency>
如果需要导出JVM运行指标,额外引入Hotspot指标依赖:
<dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient_hotspot</artifactId> <version>0.16.0</version> </dependency>
2. 编写/metrics端点代码
直接基于现有javax.ws.rs规范定义端点,输出Prometheus要求的标准格式指标:
import io.prometheus.client.CollectorRegistry; import io.prometheus.client.exporter.common.TextFormat; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import java.io.StringWriter; @Path("/metrics") public class PrometheusMetricsResource { @GET public Response exportMetrics() { try { StringWriter writer = new StringWriter(); // 按照Prometheus标准格式输出所有注册的指标 TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); return Response.ok(writer.toString()) .header("Content-Type", TextFormat.CONTENT_TYPE_004) .build(); } catch (Exception e) { return Response.serverError().entity("Failed to export metrics").build(); } } }
3. 初始化配置
- 所有自定义的Counter、Gauge、Histogram等指标,只要注册到
CollectorRegistry.defaultRegistry就会自动出现在指标输出中 - 如果需要导出JVM指标,在应用启动逻辑中执行一次初始化即可:
import io.prometheus.client.hotspot.DefaultExports; // 应用启动时调用一次 DefaultExports.initialize();
- 如果你现有代码中使用的
@Timed是Dropwizard Metrics的注解,可额外引入simpleclient_dropwizard依赖,将已有Dropwizard指标自动桥接到Prometheus,无需重复埋点。
方案优势
- 完全兼容现有javax.ws.rs技术栈,不需要引入Spring等额外组件
- 复用应用现有服务端口,不需要单独占用端口启动Prometheus导出服务
- 指标格式完全符合Prometheus官方规范,和独立HTTPServer导出的效果完全一致
内容的提问来源于stack exchange,提问作者Alk
相关产品推荐
相关产品推荐

