Spring Boot 2集成EhCache3/JCache,如何在Actuator端点展示缓存监控指标?
解决Spring Boot 2中JCache+EhCache 3在Actuator Caches端点展示指标的问题
核心问题原因
Actuator的caches端点默认仅展示缓存基础信息(如目标类),不会自动暴露缓存统计指标,需开启端点的详细信息展示,同时确保缓存统计已正确启用并被Spring Boot识别。
解决方案步骤
1. 开启Caches端点的详细信息展示
在application.properties或application.yml中添加配置,让端点返回缓存的详细统计数据:
application.properties
management.endpoint.caches.show-details=always management.endpoints.web.exposure.include=caches
application.yml
management: endpoint: caches: show-details: always endpoints: web: exposure: include: caches
2. 确保缓存统计正确启用并适配
调整缓存管理器代码,直接在缓存配置中启用统计,让Spring Boot能更可靠地识别统计数据:
@Bean public CacheManager ehCacheManager() { CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); cacheManager.destroyCache("cache1"); // 构建缓存配置时直接启用统计 CacheConfiguration<String, Integer> cacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, Integer.class, ResourcePoolsBuilder.heap(1000) ) .withStatisticsEnabled() .build(); cacheManager.createCache("cache1", Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfig)); return new JCacheCacheManager(cacheManager); }
3. 验证依赖完整性
确保项目依赖包含必要组件:
Maven
<!-- Spring Boot Cache Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- EhCache 3 JSR107 实现 --> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <!-- Spring Boot Actuator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
验证结果
重启应用后访问localhost:8080/actuator/caches,每个缓存条目将新增statistics字段,包含命中率、缓存大小、命中/未命中次数等详细指标。
内容的提问来源于stack exchange,提问作者Herry
相关产品推荐
相关产品推荐

