您好,登錄后才能下訂單哦!
Go中的HashMap緩存失效策略通常有以下幾種:
container/list
包實(shí)現(xiàn)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
包實(shí)現(xiàn)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
}
這些策略可以根據(jù)具體需求進(jìn)行選擇和組合,以實(shí)現(xiàn)高效的緩存失效機(jī)制。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。