ehcache xml需要defaultCache元素,而其他缓存正在获取defaultCache属性

问题描述 投票:1回答:2

这就是我的ehcache.xml的样子:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="false" name="defaultCache1">
    <diskStore path="java.io.tmpdir" />
    <defaultCache name="defaultCache" maxElementsInMemory="10000" eternal="false" statistics="true" timeToIdleSeconds="10"
        timeToLiveSeconds="10" overflowToDisk="false" diskPersistent="false" memoryStoreEvictionPolicy="LRU" /> 

    <cache name="PreferenceValueEntity" eternal="false" maxElementsInMemory="1000"
        timeToIdleSeconds="5" timeToLiveSeconds="5" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />
</ehcache>

我的persistence.xml包含:

<!-- EHCache managed by hibernate -->           
        <property name="hibernate.cache.use_second_level_cache" value="true" />
        <property name="hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />
        <property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletonEhCacheProvider" />
        <property name="net.sf.ehcache.configurationResourceName" value="/META-INF/ehcache.xml"/>

我正在使用 - JPA和Hibernate 5.2.x - ehcache-2.10.3

问题是timeToIdleSeconds是从defaultCache继承的,因此缓存在10秒后过期而不是5秒。

  1. 我不需要defaultCache,但是从ehcache.xml中删除它会在tomcat启动时抛出异常。强制我将其添加到ehcache.xml。我知道每个ehcache文档不需要,但不确定是什么原因导致需要它。
  2. 为什么timeToLiveSeconds是从defaultCache继承的。

解决它们中的任何一个都将解决我的问题,但是如果两个问题都解决了,那就太好了。

谢谢,

java hibernate jpa ehcache
2个回答
1
投票

使用Hibernate时,需要创建相当多的缓存。除非您在配置中明确定义它们,否则将使用defaultCache机制。

这意味着当Hibernate需要缓存时,它将从CacheManager请求它,如果该缓存不存在,Ehcache将使用defaultCache定义来创建它。

所以有两个选择:

  1. 根据您的需要配置defaultCache
  2. 确定应用程序所需的所有缓存名称,并明确定义它们。

0
投票

名为PreferenceValueEntity的实体的缓存名称必须是实体的完全限定类名。例如com.my.package.PreferenceValueEntity(我不知道PreferenceValueEntity的包名是什么,所以我只是在这里弥补^^)。

所以你的配置应该是这样的:

<cache name="com.my.package.PreferenceValueEntity" eternal="false" maxElementsInMemory="1000"
        timeToIdleSeconds="5" timeToLiveSeconds="5" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />

This explanation in the ehcache documentation举了一个很好的例子。

qazxsw poi提供了一个关于使用Hibernate二级缓存的好教程。

© www.soinside.com 2019 - 2024. All rights reserved.