You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ehcache 2.10迁移至3.5.2:Element替代及缓存时间戳获取咨询

解决Ehcache 3.5.2迁移中替代Element并获取时间戳的问题

我来帮你搞定这个迁移里的问题~在Ehcache 3.x版本中,net.sf.ehcache.Element确实被完全移除了,不过我们可以通过新的API来实现相同的逻辑,分两种场景给你说明:

场景1:获取缓存值本身的时间戳(和原代码逻辑一致)

原代码中你是从缓存值对象里拿到timestamp,这个逻辑在Ehcache 3里只需要调整API调用方式即可:

替代getQuiet()的方式

如果你需要和getQuiet()一样不触发缓存命中统计的行为,可以用Cache.getEntry()方法,它会返回缓存条目对象Cache.Entry:

// 假设你的缓存键是String类型,值是自定义的Page类(对应原代码getValue()返回的对象)
Cache.Entry<String, Page> cacheEntry = basicCache.getEntry(filepath);
if (cacheEntry != null) {
    Page page = cacheEntry.getValue();
    long pageTime = page.getTimestamp(); // 和原逻辑完全一致
}

如果不需要在意统计触发,直接用Cache.get()获取ValueWrapper也可以:

ValueWrapper valueWrapper = basicCache.get(filepath);
if (valueWrapper != null) {
    Page page = (Page) valueWrapper.get();
    long pageTime = page.getTimestamp();
}

场景2:获取缓存条目的创建/更新时间(而非值对象自带的时间)

如果你的需求是获取缓存条目本身被存入/更新的时间(不是值对象自带的timestamp),Ehcache 3没有直接暴露这个属性,最简便的方式是自定义一个包装类,把值和缓存时间一起存储:

1. 定义缓存值包装类

public class CachedItem<T> {
    private T value;
    private long cacheTimestamp;

    public CachedItem(T value) {
        this.value = value;
        this.cacheTimestamp = System.currentTimeMillis(); // 存入缓存时记录时间
    }

    // Getter方法
    public T getValue() {
        return value;
    }

    public long getCacheTimestamp() {
        return cacheTimestamp;
    }
}

2. 存入缓存时使用包装类

// 存入时包裹原始值
basicCache.put(filepath, new CachedItem<>(yourPageObject));

3. 获取缓存时读取时间戳

CachedItem<Page> cachedItem = basicCache.get(filepath);
if (cachedItem != null) {
    long cacheEntryTime = cachedItem.getCacheTimestamp(); // 缓存条目存入时间
    Page page = cachedItem.getValue();
    // 也可以同时拿到值对象自带的timestamp
    long pageTime = page.getTimestamp();
}

内容的提问来源于stack exchange,提问作者Madhuri Haritha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:26:34