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

如何获取Caffeine Cache中最新插入的条目?

关于Caffeine Cache获取最新插入条目的方法

Caffeine的默认缓存实现并没有提供直接获取最新插入条目的API,因为它默认不会追踪条目插入的时间顺序信息。不过你可以通过以下两种方式实现这个需求:

方案一:自定义包装类记录插入时间

通过给缓存值包装一层,记录每个条目的插入时间,之后通过遍历缓存筛选出最新条目:

// 定义包装类,存储实际值和插入时间戳
class TimedCacheValue<V> {
    private final V value;
    private final long insertTimestamp;

    public TimedCacheValue(V value) {
        this.value = value;
        this.insertTimestamp = System.currentTimeMillis();
    }

    public V getValue() {
        return value;
    }

    public long getInsertTimestamp() {
        return insertTimestamp;
    }
}

// 修改缓存配置,存储包装后的类型
Caffeine<Object, TimedCacheValue<Object>> caffeineCacheBuilder() {
    return Caffeine.newBuilder()
        .initialCapacity(100)
        .expireAfterWrite(Duration.ofHours(50));
}

// 插入缓存时用包装类包裹值
cache.put("key1", new TimedCacheValue<>("value1"));

// 获取最新插入的条目
Optional<Map.Entry<Object, TimedCacheValue<Object>>> latestEntry = cache.asMap().entrySet().stream()
    .max(Comparator.comparingLong(entry -> entry.getValue().getInsertTimestamp()));

// 提取结果
latestEntry.ifPresent(entry -> {
    Object latestKey = entry.getKey();
    Object latestValue = entry.getValue().getValue();
    // 处理最新条目
});

方案二:基于有序Map维护插入顺序

利用LinkedHashMap的插入顺序特性,让Caffeine使用它作为底层存储,直接通过有序Map的特性获取最新条目:

// 配置缓存使用LinkedHashMap维护插入顺序
Caffeine<Object, Object> caffeineCacheBuilder() {
    return Caffeine.newBuilder()
        .initialCapacity(100)
        .expireAfterWrite(Duration.ofHours(50))
        .build(() -> new LinkedHashMap<>(16, 0.75f, false) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
                // 控制缓存最大容量,和initialCapacity对应
                return size() > 100;
            }
        });
}

// 获取最新插入条目(LinkedHashMap的最后一个key对应最新插入的条目)
Map<Object, Object> cacheMap = cache.asMap();
Object latestKey = null;
for (Object key : cacheMap.keySet()) {
    latestKey = key;
}
if (latestKey != null) {
    Object latestValue = cacheMap.get(latestKey);
    // 处理最新条目
}

注意:第二种方案中LinkedHashMap的第三个构造参数设为false时维护插入顺序,设为true则维护访问顺序,需根据需求调整。如果缓存条目数量较多,遍历获取最新条目的操作会有性能开销,若频繁需要该操作,建议单独维护一个和缓存同步更新的队列,直接从队列尾部获取最新插入的key。

内容的提问来源于stack exchange,提问作者Akhmad Zaki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:42:38