您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。