Hibernate的二级缓存常使用Ehcache实现,而ehcache.xml就是控制缓存行为的核心配置文件。搞清楚它的结构,才能避免内存溢出和缓存失效问题。

ehcache.xml基本结构
一个标准的ehcache.xml主要包含三个部分:磁盘存储路径配置、默认缓存策略、以及针对具体实体类的缓存策略。
核心标签说明
<diskStore>:指定缓存数据写入磁盘的目录,当内存不足时Ehcache会把对象刷到此处。<defaultCache>:默认缓存模板,未单独配置的类都会套用这个规则。<cache>:为某个实体或查询单独设置缓存参数,name必须唯一。
常用配置参数含义
| 参数 | 作用 |
|---|---|
| maxElementsInMemory | 内存中最多存放的对象数量 |
| eternal | 是否永久有效,true则忽略过期设置 |
| timeToIdleSeconds | 对象空闲多少秒后失效 |
| timeToLiveSeconds | 对象创建后存活的最大秒数 |
| overflowToDisk | 内存满时是否写到磁盘 |
完整配置示例
下面是一份可直接使用的ehcache.xml示例,注意里面的特殊字符都已转义:
<?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"/>
<!-- 默认缓存策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="300"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<!-- 用户实体单独配置 -->
<cache name="com.example.entity.User"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="180"
overflowToDisk="true"/>
</ehcache>
在Hibernate中启用
写好文件后,还要在hibernate.cfg.xml里开启二级缓存并指定提供者:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">
ehcache.xml
</property>
注意事项
缓存的name值要与Hibernate实体类的全限定名一致,否则会找不到配置而使用默认策略。生产环境建议把overflowToDisk设为false,使用分布式缓存替代本地磁盘。
按照上面的模板修改路径和数量参数,就能快速搭好Hibernate二级缓存的基础环境。
Hibernate二级缓存ehcache_xml修改时间:2026-07-27 20:48:19