You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何将Dropwizard metrics转换为Prometheus兼容格式

解决方案

你当前注册的是Dropwizard Metrics原生的MetricsServlet,默认输出JSON格式指标,而Prometheus仅支持基于文本的专属指标 exposition 格式,无法直接解析JSON输出,需要通过Dropwizard到Prometheus的适配桥接组件完成格式转换,配置步骤如下:

1. 引入Prometheus适配依赖

在项目构建配置中引入和你当前Dropwizard Metrics版本匹配的Prometheus桥接包,你当前返回的metrics版本为4.0.0,直接使用对应版本即可,Maven配置示例:

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-prometheus</artifactId>
    <version>4.0.0</version>
</dependency>

注意:版本号必须和项目中已引入的metrics-core版本保持一致,避免出现指标转换兼容问题。

2. 替换原有MetricsServlet注册逻辑

删除你之前注册Dropwizard原生MetricsServlet的Bean,改为注册Prometheus提供的指标Servlet,同时将已有的DropwizardMetricRegistry绑定到Prometheus的收集器注册表中,代码示例:

import com.codahale.metrics.MetricRegistry;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.dropwizard.DropwizardExports;
import io.prometheus.client.exporter.MetricsServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PrometheusMetricsConfig {

    @Bean
    public CollectorRegistry prometheusCollectorRegistry(MetricRegistry dropwizardMetricRegistry) {
        CollectorRegistry registry = CollectorRegistry.defaultRegistry;
        // 将Dropwizard中存储的所有指标桥接到Prometheus收集器
        registry.register(new DropwizardExports(dropwizardMetricRegistry));
        return registry;
    }

    @Bean
    public ServletRegistrationBean<MetricsServlet> registerPrometheusMetricsServlet(CollectorRegistry collectorRegistry) {
        // 注意:此处导入的是io.prometheus.client.exporter路径下的MetricsServlet,不要和原来Dropwizard的同名类混淆
        return new ServletRegistrationBean<>(new MetricsServlet(collectorRegistry), "/metrics");
    }
}

3. 验证配置结果

重启应用后再次访问localhost:8080/metrics,会返回Prometheus标准的文本格式指标输出,示例如下:

# HELP counter_total Generated from Dropwizard metric import (metric=counter, type=com.codahale.metrics.Counter)
# TYPE counter_total counter
counter_total 36.0

该格式可以直接被Prometheus正常识别采集。

注意事项

  • 导入MetricsServlet时务必确认包路径,误用com.codahale.metrics.servlets.MetricsServlet会持续返回原有JSON格式。
  • 如果项目后续引入Spring Boot Actuator,也可以直接使用Actuator内置的Prometheus端点,上述手动注册Servlet的方式改动最小,无需额外引入Actuator依赖。

内容的提问来源于stack exchange,提问作者gstackoverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 15:31:15