lru缓存算法

LRU 缓存算法基于一个基本假设:如果一个数据长时间没有被访问,那么它未来也很可能不会再被访问。因此,当缓存达到上限时,应该淘汰掉最久未被访问的数据。

  • 过期时间:缓存项有一个时间戳(timestamp),每次访问时都会重新设置一个新的过期时间 maxAge,如果缓存项超过 maxAge 设定的过期时间就会被删除。
  • 最大缓存大小限制:当缓存数量超过 maxSize 时,会删除最早插入的缓存项(即最旧的项),这类似于 LRU 缓存的淘汰策略。
  • 如何获取到最早插入的缓存项的key:通过mapObj.keys().next().value
class LRUCache {
    constructor(maxSize, maxAge) {
      //缓存数量
      this.maxSize = maxSize;
      //缓存毫秒数
      this.maxAge = maxAge;
      this.cache = new Map();
      this.timer = null;
    }
    /**
     * 判断缓存key是否过期,过期则删除
     * 未过期的缓存,延长寿命
    */
    get(key) {
      const item = this.cache.get(key);
      if (item) {
        clearTimeout(item.timer);
        const now = new Date().getTime();
        //判断缓存是否过期
        if (now - item.timestamp > this.maxAge) {
          this.cache.delete(key);
          return undefined;
        }
        //重新记录过期时间
        this.cache.delete(key);
        this.cache.set(key, { value: item.value, timestamp: now, timer: setTimeout(() => this.cache.delete(key), this.maxAge) });
        return item.value;
      }
      return undefined;
    }
    /** 
     * 缓存大小超出限制时删除最旧的缓存。(即最先插入的)
     * 缓存数据时,用计时器实现自动过期逻辑
    */
    set(key, value) {
      const now = new Date().getTime();
      if (this.cache.size >= this.maxSize) {
        const oldestKey = this.cache.keys().next().value;
        this.cache.delete(oldestKey);
      }
      this.cache.set(key, { value, timestamp: now, timer: setTimeout(() => this.cache.delete(key), this.maxAge) });
    }
  
    clear() {
      this.cache.clear();
    }
  }

  

posted @ 2025-02-08 09:53  我是格鲁特  阅读(110)  评论(0)    收藏  举报