我在play Framework2.5.6中设置缓存,并使用timeToIdle属性进行挣扎。
我的配置遵循官方文档中提供的配置
conf/ehcache.xml:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<cache name="userSession"
maxEntriesLocalHeap="100000"
maxEntriesLocalDisk="10000"
eternal="false"
diskSpoolBufferSizeMB="30"
memoryStoreEvictionPolicy="LRU"
timeToIdleSeconds="3"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>conf/application.conf.conf:
play.cache {
bindCaches = ["userSession"]
createBoundCaches = false
}在代码中,我通过使用@Inject @NamedCache("userSession")注入来获得缓存。
缓存是注入的,可以使用,但据我观察,没有使用timeToIdleInSeconds。
我的配置是确定的,因为我可以在日志中找到:
2016-10-21 11:46:46,086 DEBUG n.s.e.config.ConfigurationFactory ForkJoinPool-1-worker-1 [] - Configuring ehcache from URL: file:/src/LR/lr-facade/target/scala-2.11/classes/ehcache.xml我尝试过调试代码,并发现在EhCache的play实现中有以下内容:
play-cache_2.11-2.5.6-sources.jar!/play/api/cache/Cache.scala
def set(key: String, value: Any, expiration: Duration) = {
val element = new Element(key, value)
expiration match {
case infinite: Duration.Infinite => element.setEternal(true)
case finite: FiniteDuration =>
val seconds = finite.toSeconds
if (seconds <= 0) {
element.setTimeToLive(1)
} else if (seconds > Int.MaxValue) {
element.setTimeToLive(Int.MaxValue)
} else {
element.setTimeToLive(seconds.toInt)
}
}
cache.put(element)
}如您所见,如果不提供ttl,eternal设置为true。根据我在EhCache 文档中所读到的,如果设置了永恒,那么整个缓存、ttl和tti就不再重要了。从代码中我看到,如果为Element设置了永恒,则tti和ttl被设置为0
ehcache-core-2.6.11-sources.jar!/net/sf/ehcache/Element.java
public void setEternal(final boolean eternal) {
if (eternal) {
this.cacheDefaultLifespan = false;
this.timeToIdle = 0;
this.timeToLive = 0;
} else if (isEternal()) {
this.cacheDefaultLifespan = false;
this.timeToIdle = Integer.MIN_VALUE;
this.timeToLive = Integer.MIN_VALUE;
}
}有人也有同样的问题吗?有人找到解决办法了吗?
当然,我知道我可以通过在缓存中设置时间戳来解决这个问题,并检查它是否应该由myslef过期。
更新
忘了我在测试conf的过程中改变了,并移除了一段时间永恒的属性。但是,我之前所做的所有测试都证明,无论设置与否,永恒的属性都是真实的(因为它来自于playCache代码)。
发布于 2016-10-22 09:12:52
我只能确认这是Cache抽象在使用Ehcache时的行为。
除非在将条目放入Cache时显式定义过期的Cache,否则映射在映射级别被配置为永久的。这意味着任何Cache级别的过期配置实际上都会被忽略,因为映射总是指定每个映射设置。
还要注意的是,Play只提供对实时/ TTL的支持,而不是对时间空闲/ TTI的支持,我认为这是一件好事,因为TTI实际上更接近于容量控制而不是新鲜的控制。
https://stackoverflow.com/questions/40174021
复制相似问题