我有一个100项(字符串)列表,我想放入ehcache。我会让它们在1小时后过期。之后我想读取数据库并刷新缓存。
我无法找到如何做到这一点的例子?
有人知道吗?
由于
答案 0 :(得分:1)
这是CacheConfiguration中用于设置缓存中元素的实时时间的方法 http://ehcache.org/apidocs/net/sf/ehcache/config/CacheConfiguration.html#timeToLiveSeconds(long)
它在缓存的构造函数中有相应的参数 http://ehcache.org/apidocs/net/sf/ehcache/Cache.html#Cache%28java.lang.String,%20int,%20boolean,%20boolean,%20long,%20long%29
这些是particaluar缓存中元素的默认值 - 也可以为精确元素指定 http://ehcache.org/apidocs/net/sf/ehcache/Element.html#setTimeToLive(int)
以下是使用它的一个小例子:
import java.util.concurrent.TimeUnit;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhCacheFixedExpirationTest {
public static void main(String[] args) {
CacheManager cacheManager = new CacheManager();
Cache testCache = new Cache("testCache", 100, false, false, 10, 10);
cacheManager.addCache(testCache);
Element element = new Element("1", "20");
element.setTimeToLive(1);
testCache.put(element);
long start = System.nanoTime();
while (testCache.get("1") != null) {
//wait
}
System.out.println(TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS));
}
}
输出几乎总是1000,因此精度相当好。使用Ehcache 2.4.6
答案 1 :(得分:0)
注意,您也可以将SelfPopulatingCache与cache element timeout结合使用,以满足您的需求。