ehcache.xml 是 Ehcache 1.x/2.x 的 XML 配置文件,需置于 classpath 根目录;hibernate 4.x/5.2- 依赖它实现二级缓存,而 Hibernate 5.3+ 推荐 JCache 抽象层。

<p>ehcache.xml 是 Ehcache 1.x(常用于老版本 Hibernate,如 4.x)的缓存配置文件,放在 <strong>classpath 根目录</strong>(如 src/main/resources)下即可被 Hibernate 自动加载。注意:Ehcache 2.x 仍兼容此格式;Ehcache 3.x 已弃用 XML 配置,改用 java 或 YAML,且 Hibernate 5.3+ 默认推荐使用 JCache(jsR-107)抽象层。</p> <H3>基础 ehcache.xml 结构(适配 Hibernate 4.x / 5.2 及以下)</H3> <p>以下是最简可用、符合 Hibernate 二级缓存要求的配置示例:</p> <pre class="brush:php;toolbar:false;"><font size="2"><?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <!-- 磁盘缓存路径,需确保应用有写权限 --> <diskStore path="java.io.tmpdir/ehcache"/> <!-- 默认缓存策略(Hibernate 未显式指定缓存策略时使用)--> <defaultCache maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> <!-- 为具体实体类或集合配置缓存(必须)--> <cache name="com.example.User" maxEntriesLocalHeap="500" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="300" overflowToDisk="true"/> <!-- 缓存集合(如 User.roles)--> <cache name="com.example.User.roles" maxEntriesLocalHeap="100" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="120" overflowToDisk="true"/> </ehcache></font>
关键配置项说明
- diskStore path:建议用
java.io.tmpdir/ehcache或绝对路径(如/var/cache/myapp/ehcache),避免硬编码用户目录 - maxEntriesLocalHeap:堆内最大缓存条目数,避免 OOM;按实体热度合理设置,不要盲目调大
- eternal=”false”:必须设为 false,否则 timeToIdleSeconds / timeToLiveSeconds 不生效
- timeToIdleSeconds:对象空闲多久后过期(不被访问)
- timeToLiveSeconds:对象创建后多久强制过期(不管是否访问)
- overflowToDisk:堆满后是否溢出到磁盘(开启需确保 diskStore 可写)
- cache name:必须与实体类全限定名(
package.ClassName)或集合属性路径(package.ClassName.propertyName)完全一致
Hibernate 端需配合的配置
仅配置 ehcache.xml 不够,还需在 Hibernate 配置中启用二级缓存:
- hibernate.cfg.xml 或 application.properties 中添加:
<font size="2"><property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- 或用 SingletonEhCacheRegionFactory(单例模式,适合单应用)--></font>
- 实体类上标注缓存策略:
<font size="2">@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) // 或 READ_ONLY, NONSTRICT_READ_WRITE public class User { ... }</font>
常见问题提醒
- 类名拼写错误(大小写、包名)、集合路径写成
User.roles而非com.example.User.roles→ 缓存不生效 - 忘记在实体类加
@Cache注解 → 即使配置了 cache name 也无效 - Ehcache jar 版本与 Hibernate 不匹配(如 Hibernate 4.3.x 应用 ehcache-core 2.6.x,不兼容 3.x)
- 未设置
hibernate.cache.use_second_level_cache=true→ 二级缓存被忽略
基本上就这些。配置不复杂但容易忽略细节,建议配完后通过日志(开启 org.hibernate.cache DEBUG)验证缓存命中情况。