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>java.io.tmpdir/ehcache 或绝对路径(如 /var/cache/myapp/ehcache),避免硬编码用户目录package.ClassName)或集合属性路径(package.ClassName.propertyName)完全一致仅配置 ehcache.xml 不够,还需在 Hibernate 配置中启用二级缓存:
<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 也无效hibernate.cache.use_second_level_cache=true → 二级缓存被忽略基本上就这些。配置不复杂但容易忽略细节,建议配完后通过日志(开启 org.hibernate.cache DEBUG)验证缓存命中情况。
以上就是Hibernate二级缓存ehcache.xml配置文件怎么写的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号