t),
}
}
// remove 通过 *list.Element 删除
func (c *Cache) remove(e *list.Element) {
n, ok := c.list.Remove(e).(*entry)
if ok {
delete(c.pond, n.key)
}
}
// Set 添加缓存
func (c *Cache) Set(key, value interface{}) {
c.m.Lock()
defer c.m.Unlock()
if e, ok := c.pond[key]; ok {
if value == nil {
// Set key nil <=> Remove key
c.remove(e)
} else {
e.Value = value
c.list.MoveToFront(e)
}
return
}
// 如果是首次添加
c.pond[key] = c.list.PushFront(&entry{key, value})
// 如果超出池子缓存开始清理
if c.max != 0 && uint(c.list.Len()) > c.max {
c.remove(c.list.Back())
}
}
// Get 获取缓存
func (c *Cache) Get(key interface{}) (interface{}, bool) {
c.m.Lock()
defer c.m.Unlock()
if e, ok := c.pond[key]; ok {
c.list.MoveToFront(e)
return e.Value.(*entry).value, true
}
return nil, false
}
用起来很容易
c := cache.New(1)
c.Set("123", "123")
c.Set("234", "234")
fmt.Println(c.Get("123"))
fmt.Println(c.Get("234"))
是不是离开了 C, 整个世界也很简单. 没啥设计模式, 有的是性能还可以, 也能用.
希望能帮到有心人 ~
后记 - 那个打开的大门
你曾是少年 - https://music.163.com/#/song?id=426027293
每个男人心里都有一块净土, 只不过生活所逼硬生生的, 藏在心底最深处 . ... ..