ehcache.xml 是 ehcache 2.x 的声明式 xml 配置文件,对应 net.sf.ehcache.config.configuration;ehcache 3.x 已弃用该格式,改用基于 jsr-107 的新 schema,spring boot 2.0+ 默认集成 3.x,旧版配置多为遗留或误配。

ehcache.xml 是什么?它不是必须存在的文件
ehcache.xml 是 Ehcache 2.x 版本中用于声明式配置缓存行为的 XML 文件,本质是 net.sf.ehcache.config.Configuration 的序列化表达。Ehcache 3.x 已彻底弃用该格式,改用 ehcache.xml(注意:3.x 的同名文件结构完全不同,且基于 JSR-107 和自定义 schema),而 Spring Boot 2.0+ 默认集成的是 Ehcache 3,**如果你在项目里看到旧版 ehcache.xml,大概率是遗留系统或误配了依赖版本**。
如何判断你用的是 Ehcache 2 还是 3?看依赖和类路径
检查你的 pom.xml 或 build.gradle:
- Ehcache 2:依赖坐标为
net.sf.ehcache:ehcache,主配置类是net.sf.ehcache.CacheManager - Ehcache 3:依赖坐标为
org.ehcache:ehcache,主配置类是org.ehcache.config.Configuration,且不识别旧版ehcache.xml的 DTD
运行时若抛出 CacheException: Unable to load class net.sf.ehcache.config.Configuration 却又没引入 2.x 依赖,说明你混用了 API 和配置格式。
旧版 ehcache.xml 常见配置项与易错点
仅适用于 Ehcache 2.x。典型结构包含 <diskstore></diskstore>、<defaultcache></defaultcache>、<cache></cache> 等节点。关键陷阱如下:
立即学习“Java免费学习笔记(深入)”;
-
<diskstore path="java.io.tmpdir"></diskstore>中的path必须是绝对路径或合法变量,java.io.tmpdir是占位符,实际会被 JVM 替换 —— 但若磁盘空间不足或权限不对,OverflowToDisk会静默失效 -
<cache name="userCache" maxelementsinmemory="1000" ...></cache>的name必须与代码中cacheManager.getCache("userCache")完全一致,大小写敏感 -
timeToIdleSeconds和timeToLiveSeconds同时设为 0 表示永不过期,但eternal="true"优先级更高,会覆盖这两个值 - 未显式定义
<defaultcache></defaultcache>时,Ehcache 2.x 会使用内置默认策略(maxElementsInMemory=10000,eternal=false),容易导致内存暴涨
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="/var/tmp/ehcache"/>
<defaultCache
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
diskPersistent="false"/>
<cache name="orderCache"
maxElementsInMemory="200"
timeToIdleSeconds="120"
timeToLiveSeconds="300"/>
</ehcache>
Spring 环境下怎么加载 ehcache.xml?别硬编码路径
Spring 2.x–4.x 可通过 ehcache:config 命名空间或 net.sf.ehcache.config.ConfigurationFactory 加载,但强烈建议用 Spring 的抽象层:
- 用
org.springframework.cache.ehcache.EhCacheManagerFactoryBean,设置configLocation属性指向 classpath 路径,例如:classpath:ehcache.xml - 不要写成
file:/opt/config/ehcache.xml—— 这会导致部署到容器(如 Tomcat)时因路径不可控而失败 - 如果使用 Spring Boot 1.x(已 EOL),可通过
spring.cache.ehcache.config=classpath:ehcache.xml指定;但 Boot 2.x+ 默认不支持 Ehcache 2,强行启用需排除spring-boot-starter-cache默认实现并手动引入 2.x 依赖,风险高
真实项目中,缓存策略的动态调整(比如灰度降级)、多环境差异(dev/staging/prod)很难靠静态 XML 覆盖,更推荐用 Java Config + Builder 模式构造 CacheManager,把过期时间、容量等作为配置项注入。










