Spring Boot项目从EhCache 2迁移至EhCache 3,如何获取缓存监控指标?
EhCache 3迁移后实现缓存监控(条目数、堆内存大小)
我正在将Spring Boot Java应用从EhCache 2迁移至EhCache 3,需要获取缓存条目数(对应EhCache 2中Prometheus的cache_size指标)及堆内存大小(对应cache_local_heap_size_bytes指标)用于缓存监控。以下是现有配置文件,请问如何在EhCache 3中实现该需求?
现有配置
EhCache XML配置
<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:jsr107='http://www.ehcache.org/v3/jsr107' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation=" http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.1.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.1.xsd"> <service> <jsr107:defaults enable-management="false" enable-statistics="true"/> </service> <cache-template name="default"> <expiry> <ttl>600</ttl> </expiry> </cache-template> <cache alias="employee" uses-template="default"> <resources> <heap>1000</heap> </resources> </cache> <cache alias="org" uses-template="default"> <key-type>java.lang.String</key-type> <resources> <heap>4000</heap> </resources> </cache> </config>
application.yml配置
cache: jcache: config: classpath:ehcache.xml
实现方案
1. 开启EhCache 3的管理与统计功能
修改EhCache XML配置中的jsr107:defaults节点,将enable-management设为true(开启后才能让监控组件获取缓存的管理类指标):
<service> <jsr107:defaults enable-management="true" enable-statistics="true"/> </service>
2. 添加监控依赖
确保项目中引入Spring Boot Actuator和Micrometer Prometheus注册表依赖(Maven示例):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency>
3. 配置Spring Boot监控端点
在application.yml中添加Prometheus端点暴露配置,让指标可以被Prometheus抓取:
management: endpoints: web: exposure: include: prometheus # 暴露prometheus端点 metrics: enable: jcache: true # 开启JCache指标收集
4. 验证指标
启动应用后,访问http://<your-app-host>:<port>/actuator/prometheus,即可找到对应的监控指标:
- 缓存条目数:
jcache_cache_size{cache="employee",...}、jcache_cache_size{cache="org",...}(对应原EhCache 2的cache_size) - 堆内存大小:
jcache_cache_local_heap_size_bytes{cache="employee",...}、jcache_cache_local_heap_size_bytes{cache="org",...}(对应原EhCache 2的cache_local_heap_size_bytes)
内容的提问来源于stack exchange,提问作者flowAlong
相关产品推荐
相关产品推荐

