实现支持时间戳查询、同key保留旧值的缓存及未命中返回旧值逻辑
带时间版本的自定义缓存实现方案
现有代码的核心问题
- 存储结构不满足基础需求:当前
memory为单key映射单缓存对象的HashMap结构,每次add同key时会直接覆盖旧值,无法留存历史版本 - 代码存在大量拼写/语法错误:包含方法名、变量名拼写偏差,循环全量遍历内存匹配key的低效逻辑
- 查询无兜底逻辑:仅做时间戳精确匹配,没有匹配不到时返回最近旧值的处理分支
具体实现调整步骤
- 调整存储结构:将内存容器改为
Map<Integer, List<TimeCaches>>,同一个key的所有历史版本按写入顺序存在列表中,新增同key记录时直接追加到列表,不覆盖旧数据 - 修正
add方法:修正所有拼写错误,生成当前时间戳作为新版本的版本标识,计算对应哈希后,将新缓存版本追加到对应key的版本列表中 - 重构
gets查询逻辑:- 先根据传入的key取出对应的全版本列表,key不存在则直接返回null
- 遍历该key下的所有缓存版本,找到和传入timestamp完全匹配的条目时,直接返回对应缓存值
- 遍历完成未找到精确匹配项时,筛选出所有时间戳小于等于查询时间的版本,取其中时间最接近查询时间的条目作为旧值返回
- 如果所有版本的时间都晚于查询时间,说明查询时间点之前不存在对应缓存,返回null
核心修正代码示例
// 调整后的存储结构 private final Map<Integer, List<TimeCaches>> memory = new HashMap<>(); @Override public void add(Integer key, String value) throws NoSuchAlgorithmException { Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis()); String hash = encryptHash(key, currentTimestamp); TimeCaches newCache = new TimeCaches(key, currentTimestamp, hash, value); // 同key追加版本,保留所有历史值 memory.computeIfAbsent(key, k -> new ArrayList<>()).add(newCache); } @Override public String gets(Integer key, Timestamp queryTimestamp) { List<TimeCaches> versionList = memory.get(key); if (versionList == null || versionList.isEmpty()) { return null; } TimeCaches nearestOldValue = null; for (TimeCaches cache : versionList) { Timestamp cacheTime = cache.getTimestamp(); // 精确匹配指定时间戳,直接返回 if (cacheTime.equals(queryTimestamp)) { return cache.getValue(); } // 筛选时间早于查询时间的最近旧版本 if (cacheTime.before(queryTimestamp)) { if (nearestOldValue == null || cacheTime.after(nearestOldValue.getTimestamp())) { nearestOldValue = cache; } } } // 未匹配到精确时间时,返回找到的最近旧值 return nearestOldValue != null ? nearestOldValue.getValue() : null; }
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

