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

Spring Boot 2.x升级后如何向Prometheus暴露缓存指标?

嘿,我之前帮同事排查过几乎一模一样的问题——Spring Boot升级到2.x后,Micrometer集成的缓存指标突然失踪了,给你列几个关键排查点,应该能帮你找回来那些缓存大小和命中率的数据:

1. 先把依赖核对清楚

Spring Boot 2.0.1对应的Micrometer版本是1.0.3,别用错版本号,否则很容易出现兼容性问题。确保你的pom.xml(或build.gradle)里有这两个核心依赖:

<!-- Prometheus registry for Micrometer -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.0.3</version>
</dependency>
<!-- Spring Cache Starter,必须存在才能触发缓存指标的自动配置逻辑 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2. 检查自动配置有没有被误关

有时候项目里的自定义配置会不小心排除掉CacheMetricsAutoConfiguration,去你的启动类看看有没有类似这样的代码:

@SpringBootApplication(exclude = {CacheMetricsAutoConfiguration.class})

如果有的话,赶紧把这个排除项删掉——这个自动配置类是Micrometer收集缓存指标的核心入口。

3. 核对配置属性

虽然默认情况下缓存指标是开启的,但保险起见,在application.properties(或yml)里明确加上这些配置:

# 暴露Prometheus端点,这个你可能已经配置了,但再确认下
management.endpoints.web.exposure.include=prometheus
# 强制开启缓存指标收集
management.metrics.enable.cache=true
# 如果只想监控特定缓存,可以指定名称,多个用逗号分隔
# management.metrics.cache.names=userCache,productCache

4. 自定义CacheManager的特殊处理

如果你的项目用了自定义的CacheManager(比如Caffeine、Ehcache,不是Spring Boot自动生成的),那Micrometer的自动绑定可能失效了,需要手动写个Binder把CacheManager和Micrometer关联起来。举个Caffeine的例子:

import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.cache.CacheMeterBinder;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.interceptor.CacheMeterBinderProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CacheMetricsConfig {
    @Bean
    public CacheMeterBinderProvider<CaffeineCache> caffeineCacheMeterBinderProvider() {
        return cache -> CacheMeterBinder.monitor(Metrics.globalRegistry, cache, cache.getName());
    }
}

换成Ehcache的话,只需要把CaffeineCache换成Ehcache就行,逻辑是完全一致的。

5. 确认缓存实例真的初始化了

Micrometer只能监控已经存在的缓存实例,所以先确认你的缓存是正常创建的。启动应用时看日志,有没有类似Creating cache instance named 'xxx'的日志输出。如果缓存根本没初始化,那肯定看不到指标。

最后验证

启动应用后,访问/actuator/prometheus,用浏览器的搜索功能找cache_size、cache_hit_ratio、cache_gets_total这些关键词,应该就能看到对应的指标了。如果还是没有,打开Debug级别的日志,搜索CacheMetrics或Micrometer,看看有没有初始化失败的错误信息,应该能快速定位问题根源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:32:59