Go中的HashMap缓存失效策略通常有以下几种:
container/list
包实现LRU缓存。type LRUCache struct {
capacity int
cache map[int]*list.Element
list *list.List
}
type entry struct {
key int
value int
}
func NewLRUCache(capacity int) *LRUCache {
return &LRUCache{
capacity: capacity,
cache: make(map[int]*list.Element),
list: list.New(),
}
}
func (c *LRUCache) Get(key int) int {
if elem, ok := c.cache[key]; ok {
c.list.MoveToFront(elem)
return elem.Value.(*entry).value
}
return -1
}
func (c *LRUCache) Put(key int, value int) {
if elem, ok := c.cache[key]; ok {
c.list.MoveToFront(elem)
elem.Value.(*entry).value = value
} else {
if len(c.cache) >= c.capacity {
lastElem := c.list.Back()
delete(c.cache, lastElem.Value.(*entry).key)
c.list.Remove(lastElem)
}
newElem := c.list.PushFront(&entry{key: key, value: value})
c.cache[key] = newElem
}
}
time
包实现TTL缓存。type TTLCache struct {
capacity int
cache map[int]*entry
ttl time.Duration
}
type entry struct {
key int
value int
expiresAt time.Time
}
func NewTTLCache(capacity int, ttl time.Duration) *TTLCache {
return &TTLCache{
capacity: capacity,
cache: make(map[int]*entry),
ttl: ttl,
}
}
func (c *TTLCache) Get(key int) int {
if elem, ok := c.cache[key]; ok && time.Now().Before(elem.expiresAt) {
return elem.value
}
return -1
}
func (c *TTLCache) Put(key int, value int) {
if elem, ok := c.cache[key]; ok {
c.remove(elem)
} else if len(c.cache) >= c.capacity {
c.remove(c.list.Back())
}
c.add(key, value)
}
func (c *TTLCache) remove(elem *list.Element) {
c.list.Remove(elem)
delete(c.cache, elem.Value.(*entry).key)
}
func (c *TTLCache) add(key int, value int) {
expiresAt := time.Now().Add(c.ttl)
newElem := c.list.PushFront(&entry{key: key, value: value, expiresAt: expiresAt})
c.cache[key] = newElem
}
这些策略可以根据具体需求进行选择和组合,以实现高效的缓存失效机制。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。