我使用 ehcache 为 Spring 应用程序中的某些实体配置了二级 hibernate 缓存。
缓存应该存在 10 分钟,但缓存的实体似乎不会存在那么久。
我的实体看起来像这样:
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "eh_apples")
public class Apple {
...
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "eh_eaters")
@ManyToMany(fetch = FetchType.EAGER)
private Set<AppleEater> eaters = new HashSet<AppleEater>();
....
}
persistence.xml 的一部分:
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_minimal_puts" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<property name="hibernate.cache.provider_configuration_file_resource_path" value="META-INF/ehcache.xml"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"></property>
ehcache.xml:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true"
maxBytesLocalHeap="500M">
<diskStore path="java.io.tmpdir/ehcache" />
<cache
name="eh_apples"
eternal="false"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"
timeToLiveSeconds="600">
<persistence strategy="localTempSwap" />
</cache>
<cache
name="eh_eaters"
eternal="false"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"
timeToLiveSeconds="600">
<persistence strategy="localTempSwap" />
</cache>
<cache
name="org.hibernate.cache.internal.StandardQueryCache"
eternal="false"
timeToLiveSeconds="600">
<persistence strategy="localTempSwap" />
</cache>
<cache
name="org.hibernate.cache.spi.UpdateTimestampsCache"
eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
在本地主机上:
第一次从数据库检索500个苹果时,大约需要1000毫秒。日志显示它们已放入内存中。 然后,对于以下一些请求,它不再访问数据库,而是从内存中读取它们。
不到 10 分钟后,它开始再次访问数据库以查找相同的实体,如下所示:
时间:09:37:44.143 持续时间:903
时间:09:37:53.295 持续时间: 92
时间:09:37:58.278 持续时间: 67
时间:09:38:57.701 持续时间: 61
时间:09:39:25.384 持续时间: 55
时间:09:40:10.049 持续时间: 1185
时间:09:44:21.507 持续时间: 1005
时间:09:44:24.802 持续时间:99
我想知道为什么缓存的生命周期不能超过 10 分钟。也许我在阅读 ehcache 文档时错过了一些重要部分,或者我的设置存在一些问题。
我很感激任何提示或帮助,请不要讨厌<3
编辑:运行统计
当我运行统计数据时,我收到以下警告:
2017-03-04 10:45:54,563 [tomcat-http--90] WARN net.sf.ehcache.config.ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/repo/sts-bundle/pivotal-tc-server-developer-3.2.2.RELEASE/base-instance/wtpwebapps/Apples/WEB-INF/lib/ehcache-2.10.2.2.21.jar!/ehcache-failsafe.xml
最佳答案
我的第一个猜测是您达到了 maxEntriesLocalHeap 或 maxBytesLocalHeap,这会导致驱逐。
您可以通过查看统计数据来确认这一点。
关于java - Hibernate二级缓存ehcache timeToLive太短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42574775/