sync.Mapmap

实现

构造器

type Item struct {
item interface{}
exired int64
} type Cache struct {
cache *sync.Map
limit int64
size int64
} func NewCache(limit int64) *Cache {
if limit <= 0 {
log.Panicf("cache.NewCache.limit:%+v <= 0", limit)
}
return &Cache{cache: &sync.Map{}, limit: limit}
}

接口以及实现

func (c *Cache) Get(key interface{}) (interface{}, bool) {
if val, ok := c.cache.Load(key); !ok {
return nil, false
} else if item, _ := val.(*Item); item.exired <= 0 || time.Now().Unix() < item.exired {
return item.item, true
} else {
c.cache.Delete(key)
atomic.AddInt64(&c.size, -1)
return nil, false
}
} func (c *Cache) Set(key, val interface{}, exired int64) {
if _, ok := c.cache.Load(key); ok && val != nil {
c.cache.Store(key, &Item{val, exired})
return
} else if ok && val == nil {
c.cache.Delete(key)
atomic.AddInt64(&c.size, -1)
return
} else if (c.limit <= c.size && c.deleteAnother(key)) || c.size < c.limit {
c.cache.Store(key, &Item{val, exired})
return
}
} func (c *Cache) Size() int64 {
return c.size
}

Random淘汰算法

基于 go 对 map 的无序遍历机制

func (c *Cache) deleteAnother(key interface{}) (found bool) {
c.cache.Range(func(other, value interface{}) bool {
if key == other {
return true
}
found = true
c.cache.Delete(other)
return false
})
return found
}

实例

参考

[1] Caches: LRU v. random [EB/OL]. https://danluu.com/2choices-eviction/.

Golang 随机淘汰算法缓存实现的相关教程结束。