golang-lru 逻辑

349 阅读1分钟

LRU (Least Recently Used) 缓存淘汰算法

Golang 实现方式(hashmap + linkList)

// 双向链表的元素
type Element struct {
	next, prev *Element

	
	list *List

	// 存储的内容(key-value 对)
	Value interface{}
}

  • Add方法

    • 查询hashmap是否存在key
      • 存在,将对应的element 移动到linkList 的头部,然后更新element存储的内容
      • 不存在,新创建一个element, 存储到hashmap 中,将element 放在linkList 的头部
  • Get方法

    • 查询hashmap 中是否存在key
      • 存在,将对应的element 移动到linkList的头部,,然后返回element
      • 不存在, 就返回nil
  • Contains方法

    • 查询hashmap中是否存在Key
      • 存在, 返回true
      • 不存在,返回false
  • Peek方法

    • 查询hashmap中是否存在Key
      • 存在,返回element和true

      • 不存在,返回nil 和 false

  • Remove方法

    • 查询hashmap中是否存在Key
      • 存在, 将element 从linkList 移除, 再从hashmap中移除, 返回true
      • 存在, 返回false
  • RemoveOldest方法

    • 获取linkList的尾部element
    • linkList 存在有效的element, 则移除, 然后返回element, true
    • linkList 不存在有效的element, 直接返回nil, false
  • GetOldest 方法

    • 获取linkList的尾部element
      • linkList 存在有效的element, 然后返回key-value对, true
      • linkList 不存在有效的element, 直接返回nil-nil对, false
  • Keys 方法

    • 返回linkList中从尾部到头部所有的element的key
  • Len方法

    • 返回linkList长度
  • Resize 方法

    • 计算输入size和linkList的长度的差值
      • 负, 返回0
      • 正, 从linkList尾部移除差值个数的element,同时也删除hashmap对应的element