【问题标题】:How to configure ehcache to replace expired object only upon successfully retrieving a newer version of the object如何配置 ehcache 以仅在成功检索对象的较新版本后替换过期对象
【发布时间】:2018-06-02 21:54:51
【问题描述】:

目前我正在为我的 Web 应用程序使用 Spring Web 框架。我已经实现了一个基本的 CacheConfig.java 文件,它读取 ehcache.xml 并创建一个 CacheManager 并用于从缓存中获取元素或将元素添加到缓存中。我的ehcache.cml如下:

    <cache name="Cache"
       maxEntriesLocalHeap="100"
       maxEntriesLocalDisk="0"
       eternal="false"
       diskSpoolBufferSizeMB="0"
       timeToIdleSeconds="43200"
       timeToLiveSeconds="43200"
       memoryStoreEvictionPolicy="LFU"
       >
    <persistence strategy="none"/>   

如何通过首先从后端数据库 (SOR) 中查找对象来确保刷新缓存,并且只有在成功检索后才会删除旧版本的元素?

编辑:用于刷新策略的 CacheLoader。

public class TestCacheLoader implements CacheLoader {
@Override
public Object load(Object key) throws CacheException {
    //return null;
    return load(key,null);


}

@Override
public Map loadAll(Collection keys) {
    //return null;
    return loadAll(keys,null);
}

@Override
public Object load(Object key, Object argument) {
    Object obj = null;
    try {
       obj = ReadFromDatabase(key);
    } catch (DatabaseValueNotFoundException e) {
      **How can I return the old value here?**
    }
    return obj;
}

@Override
public Map loadAll(Collection keys, Object argument) {
    //return null;
    Map newValues = new HashMap<Object,Object>();
    for(Object key : keys){
        Object value = load(key,null);
        if(value != null){
            newValues.put(key,value);
        }
    }
    return newValues;
}

@Override
public String getName() {
    return null;
}

@Override
public CacheLoader clone(Ehcache ehcache) throws CloneNotSupportedException {
    return null;
}

@Override
public void init() {

}

@Override
public void dispose() throws CacheException {

}

@Override
public Status getStatus() {
    return null;
}

}

【问题讨论】:

    标签: java caching ehcache


    【解决方案1】:

    没有开箱即用的支持来满足您的要求。

    Ehcache 2.x 支持refresh ahead,可以使用scheduled refresh ahead 进一步调整。这不是您要问的,但可能已经足够接近了。

    ** 问题编辑后的补充**

    您的编辑建议您希望保留一个陈旧的值,因为数据库不再具有该键的条目,而不是告诉用户没有值。这里同样不支持,因为它违反了缓存的原则。

    【讨论】:

    • 请看我的编辑。我不明白如何在缓存中返回旧值,因为缓存加载器无法访问它为其加载值的缓存中的值。
    猜你喜欢
    • 2010-10-11
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多