如何查看Spring Boot应用当前使用的缓存管理器(Cache Manager)?
如何确认Spring Boot中当前生效的缓存管理器
下面是几种简单直接的方式,帮你验证当前正在工作的缓存管理器是否为预期的Caffeine/Ehcache:
1. 打印缓存管理器类型
在应用中注入CacheManager并输出其类名,最直观的方式是通过CommandLineRunner在启动时打印:
import org.springframework.boot.CommandLineRunner; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CacheVerificationConfig { @Bean public CommandLineRunner cacheManagerChecker(CacheManager cacheManager) { return args -> { System.out.println("当前缓存管理器类: " + cacheManager.getClass().getName()); System.out.println("已注册的缓存名称列表: " + cacheManager.getCacheNames()); }; } }
启动应用后,控制台会输出具体的类名:
- 默认简易缓存对应
org.springframework.cache.support.SimpleCacheManager - Caffeine对应
org.springframework.cache.caffeine.CaffeineCacheManager - Ehcache对应
org.springframework.cache.ehcache.EhCacheCacheManager
2. 利用Spring Boot Actuator查看(需启用)
如果你的项目引入了Actuator依赖,开启缓存端点后可以直接通过HTTP请求查看缓存详情:
- 首先在配置文件中开启端点:
management.endpoints.web.exposure.include=caches management.endpoint.caches.enabled=true
- 启动应用后访问
http://localhost:8080/actuator/caches(端口根据你的配置调整),返回的JSON数据中会包含每个缓存对应的cacheManager信息,明确显示其类型。
3. 断点调试定位
缓存拦截的核心逻辑在Spring的CacheInterceptor类中,你可以直接在这个类的invoke方法上打断点。当被@Cacheable注解的方法执行时,程序会进入这个方法,此时你可以查看局部变量cacheManager的实例类型,确认是否为目标缓存管理器。
另外,也可以直接在目标缓存管理器的getCache方法上打断点(比如CaffeineCacheManager.getCache),当缓存被调用时会触发断点,直接验证是否是该管理器在工作。
4. 查看自动配置日志
开启Spring Boot的debug日志,观察缓存相关的自动配置过程:
在配置文件中添加:
logging.level.org.springframework.boot.autoconfigure.cache=DEBUG
启动应用后,控制台会输出缓存自动配置的匹配日志,比如匹配了CaffeineCacheConfiguration还是SimpleCacheConfiguration,由此判断是否启用了预期的缓存管理器。
内容的提问来源于stack exchange,提问作者Slevin
相关产品推荐
相关产品推荐

