文章目录
项目git地址点我
golang-lru提供了三个模块。LRU,2Q,ARC三个模块。本文主要介绍整个包的结构,以及为三个模块提供最底层功能的simplelru。
项目结构
整个项目结构非常简单,对外提供三个平行的模块在各自的文件中。simplelru提供了底层的simplelru结构,并且提供了一个lru接口。
LRUCache接口
LRUCache定义了lru缓存的方法。这里注释给的比较详细,直接照搬了。
// LRUCache is the interface for simple LRU cache.
type LRUCache interface {
// Adds a value to the cache, returns true if an eviction occurred and
// updates the "recently used"-ness of the key.
Add(key, value interface{
}) bool
// Returns key's value from the cache and
// updates the "recently used"-ness of the key. #value, isFound
Get(key interface{
}) (value interface{
}, ok bool)
// Checks if a key exists in cache without updating the recent-ness.
Contains(key interface{
}) (ok bool)
// Returns key's value without updating the "recently used"-ness of the key.
// 这里额外提供的Peek方法用来根据key获取value,并且不更新这个元素在队列中的信息
Peek(key interface{
}) (value interface{
}, ok bool)
// Removes a key from the cache.
Remove(key interface{
}) bool
// Removes the oldest entry from cache.
RemoveOldest() (interface{
}, interface{
}, bool)
// Returns the oldest entry from the cache. #key, value, isFound
GetOldest() (interface{
}, interface{
}, bool)
// Returns a slice of the keys in the cache, from oldest to newest.
Keys() []interface{
}
// Returns the number of items in the cache.
Len() int
// Clears all cache entries.
Purge()
// Resizes cache, returning number evicted
Resize(int) int
}
simplelru
entry结构
节点元素就是简单的kv结构
type entry struct {
key interface{
}
value interface{
}
}
LRU结构
典型的LRU结构,通过list + map的方式进行存储,链表用来给队列排序,方便淘汰队尾的元素,map结构保证激活元素的时候查询的复杂度为O(N)。还添加了一个回调方法当元素离开队列后被调用
type EvictCallback func(key interface{
}, value interface{