Documentation ¶
Overview ¶
Package lru implements an LRU cache.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct { MaxEntries int // maxBytes 是允许使用的最大内存 // OnEvicted optionally specifies a callback function to be // executed when an entry is purged from the cache. OnEvicted func(key Key, value interface{}) //提供一个淘汰值时的钩子函数 // contains filtered or unexported fields }
Cache is an LRU cache. It is not safe for concurrent access. groupcache的核心数据结构
func New ¶
New creates a new Cache. If maxEntries is zero, the cache has no limit and it's assumed that eviction is done by the caller. 方便实例化 Cache,实现 New() 函数
func (*Cache) Add ¶
Add adds a value to the cache. 如果键存在,则更新对应节点的值,并将该节点移到队尾。 不存在则是新增场景,首先队尾添加新节点 &entry{key, value}, 并字典中添加 key 和节点的映射关系。 更新 c.nbytes,如果超过了设定的最大值 c.maxBytes,则移除最少访问的节点。
func (*Cache) Get ¶
Get looks up a key's value from the cache. 第一步是从字典中找到对应的双向链表的节点,第二步,将该节点移动到队尾 如果键对应的链表节点存在,则将对应节点移动到队尾,并返回查找到的值。 c.ll.MoveToFront(ele),即将链表中的节点 ele 移动到队尾(双向链表作为队列,队首队尾是相对的,在这里约定 front 为队尾)
func (*Cache) RemoveOldest ¶
func (c *Cache) RemoveOldest()
RemoveOldest removes the oldest item from the cache.
type Key ¶
type Key interface{} //只要是可以用来作为比较的对象,均可以作为groupcache的key
A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators