package ttlruimport container/listtype Cache struct {MaxEntries intll *list.Listcache map[interface{}]*list.Element}func New(maxEntries int) *Cache {return Cache{MaxEntries: maxEntries,ll: ...
package ttlru
import "container/list"
type Cache struct {
MaxEntries int
ll *list.List
cache map[interface{}]*list.Element
}
func New(maxEntries int) *Cache {
return &Cache{
MaxEntries: maxEntries,
ll: list.New(),
cache: make(map[interface{}]*list.Element),
}
}
type entry struct {
key interface{}
value interface{}
}
func (c *Cache)Add(key,value interface{}) {
if c.cache == nil {
c.cache = make(map[interface{}]*list.Element)
c.ll = list.New()
}
//如果存在,则直接更新
if ee,ok := c.cache[key];ok {
c.cache[key] = ee
c.ll.MoveToFront(ee)
return
}
ele := c.ll.PushFront(&entry{
key: key,
value: value,
})
c.cache[key] = ele
if c.MaxEntries != 0 && len(c.cache) > c.MaxEntries{
c.removeElement(ele)
}
}
func (c *Cache)Get(key interface{}) (interface{},bool) {
if c.cache == nil{
return nil,false
}
if ele,hit := c.cache[key];hit{
return ele.Value.(*entry).value,true
}
return nil,false
}
func (c *Cache)Remove(key interface{}) {
if c.cache == nil{
return
}
if ele,hit := c.cache[key];hit{
c.removeElement(ele)
}
}
func (c *Cache) Clear() {
c.ll = nil
c.cache = nil
}
func (c *Cache) Len() int {
if c.cache == nil {
return 0
}
return c.ll.Len()
}
func (c *Cache)removeElement(e *list.Element) {
c.ll.Remove(e)
delete(c.cache,e.Value.(entry).key)
}
问题:线程非安全,没有加入过期时间
过期时间方案:set时设置过期时间,get时比较key是否过期,过期则删除
线程安全方案:map使用sync.Map(),链表使用读写锁加锁(通常来说,读多写少)
织梦狗教程
本文标题为:go语言lru实现
基础教程推荐
猜你喜欢
- Ruby3多线程并行Ractor使用方法详解 2023-07-23
- R语言-修改(替换)因子变量的元素操作 2022-11-26
- 浅析ELF转二进制允许把 Binary 文件加载到任意位置 2023-07-06
- R语言绘制折线图实例分析 2022-11-21
- win10下使用virtualbox + vagrant配置ruby开发机环境 2023-07-23
- ruby-on-rails-为使用Rails 4,nginx和乘客的用户设置自定义域 2023-09-21
- Swift中重写和重载的使用与对比总结 2023-07-05
- ruby on rails validates 2023-09-22
- Swift初始化器与可选链的使用方法介绍 2023-07-08
- R语言 ggplot2改变柱状图的顺序操作 2022-11-17
