You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot 2.0迁移:Prometheus指标向后兼容性疑问

不用修改现有Prometheus指标也能升级Spring Boot 2.0!

当然可以不用改动现有指标实现就完成升级,别担心——Spring Boot 2.0虽然默认采用Micrometer作为指标体系,但它提供了对旧版Prometheus客户端的兼容路径,下面是具体的实操方案:

核心思路

Spring Boot 2.0不会强制你立刻切换到Micrometer,你可以保留原有基于io.prometheus系列依赖的指标代码,通过配置调整让旧指标继续正常工作,甚至可以和Micrometer的指标共存。

具体步骤

1. 保留旧依赖与代码

  • 不要删除原有的Prometheus客户端依赖,比如io.prometheus:simpleclientio.prometheus:simpleclient_commonio.prometheus:simpleclient_hotspot这些,保持你原来的Counter、Gauge等指标定义和采集逻辑完全不变。
  • 保留你之前用来暴露指标的自定义端点(如果有的话),比如自定义的/prometheus接口。

2. 调整Spring Boot 2.0相关依赖

  • 添加Spring Boot 2.0的Actuator依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  • 如果你想同时试用Micrometer(不影响旧指标),可以添加Micrometer的Prometheus注册器依赖:
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
        <version>1.0.2</version>
    </dependency>
    

3. 配置适配

根据你的需求选择以下一种配置方式:

方式一:完全保留旧指标端点,禁用Actuator的Prometheus端点

如果想继续使用自己的旧指标暴露路径,只需在application.properties中限制Actuator暴露的端点,避免冲突:

# 只暴露必要的Actuator端点,不包含prometheus
management.endpoints.web.exposure.include=health,info

启动应用后,访问你原来的指标端点(比如/prometheus)就能看到旧指标正常输出。

方式二:合并旧指标与Micrometer指标到同一个端点

如果你想把旧指标和Micrometer生成的新指标合并到Actuator的/actuator/prometheus端点,可以注册一个自定义的CollectorRegistryCustomizer,将旧的CollectorRegistry中的指标合并到Micrometer使用的Registry中:

import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import org.springframework.boot.actuate.metrics.export.prometheus.CollectorRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PrometheusConfig {
    @Bean
    public CollectorRegistryCustomizer collectorRegistryCustomizer() {
        return registry -> {
            // 将旧Registry中的所有采集器注册到Micrometer的Registry中
            registry.register(CollectorRegistry.defaultRegistry.getSampleCollectors());
        };
    }
}

同时在配置文件中开启Actuator的Prometheus端点:

management.endpoints.web.exposure.include=health,info,prometheus
management.endpoint.prometheus.enabled=true

访问/actuator/prometheus就能同时看到旧指标和Micrometer的指标了。

额外建议

虽然这个兼容方案能让你零成本升级,但长期来看还是建议逐步迁移到Micrometer——它是Spring生态的标准指标库,支持Prometheus、Graphite、Datadog等多种监控系统,而且Spring Boot后续版本会持续优化对它的支持。不过如果暂时没时间改动,用上面的方法完全可以正常运行Spring Boot 2.0。

内容的提问来源于stack exchange,提问作者Hubert Ströbitzer

火山引擎 最新活动