溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

實(shí)戰(zhàn)Go:HashMap緩存的緩存數(shù)據(jù)訪問緩存失效處理

發(fā)布時(shí)間:2024-11-09 01:09:39 來(lái)源:億速云 閱讀:79 作者:小樊 欄目:編程語(yǔ)言

在Go中,使用sync.Map作為HashMap緩存時(shí),可能會(huì)遇到緩存失效的問題。為了解決這個(gè)問題,我們可以采用以下策略:

  1. 設(shè)置緩存過期時(shí)間:為每個(gè)緩存項(xiàng)設(shè)置一個(gè)過期時(shí)間,當(dāng)過期時(shí)間到達(dá)時(shí),自動(dòng)刪除該緩存項(xiàng)??梢允褂?code>time.AfterFunc函數(shù)來(lái)實(shí)現(xiàn)定時(shí)器功能。
package main

import (
	"fmt"
	"sync"
	"time"
)

type CacheItem struct {
	Value      interface{}
	ExpireTime time.Time
}

type LRUCache struct {
	capacity int
	cache    map[string]CacheItem
	mu       sync.Mutex
	evictList *list.List
}

func NewLRUCache(capacity int) *LRUCache {
	return &LRUCache{
		capacity: capacity,
		cache:    make(map[string]CacheItem),
		evictList: list.New(),
	}
}

func (c *LRUCache) Get(key string) (interface{}, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()

	item, ok := c.cache[key]
	if !ok || item.ExpireTime.Before(time.Now()) {
		return nil, false
	}

	c.evictList.MoveToFront(item.Value.(*list.Element))
	return item.Value, true
}

func (c *LRUCache) Put(key string, value interface{}, ttl time.Duration) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if item, ok := c.cache[key]; ok {
		c.evictList.Remove(item.Value.(*list.Element))
		delete(c.cache, key)
	} else if len(c.cache) >= c.capacity {
		lastElem := c.evictList.Back()
		delete(c.cache, lastElem.Value.(*CacheItem).Key)
		c.evictList.Remove(lastElem)
	}

	item := &CacheItem{
		Value:      value,
		ExpireTime: time.Now().Add(ttl),
	}
	itemValue := item.Value
	element := c.evictList.PushFront(itemValue)
	c.cache[key] = *item
}

func main() {
	cache := NewLRUCache(2)
	cache.Put("key1", "value1", 5*time.Second)
	cache.Put("key2", "value2", 5*time.Second)
	fmt.Println(cache.Get("key1")) // 輸出: value1 true

	time.Sleep(6 * time.Second)
	fmt.Println(cache.Get("key1")) // 輸出: <nil> false
}
  1. 使用定時(shí)任務(wù)清理過期緩存:可以使用time.Ticker來(lái)定期檢查緩存中的過期項(xiàng),并將其刪除。
package main

import (
	"fmt"
	"sync"
	"time"
)

type CacheItem struct {
	Value      interface{}
	ExpireTime time.Time
}

type LRUCache struct {
	capacity int
	cache    map[string]CacheItem
	mu       sync.Mutex
	evictList *list.List
}

func NewLRUCache(capacity int) *LRUCache {
	return &LRUCache{
		capacity: capacity,
		cache:    make(map[string]CacheItem),
		evictList: list.New(),
	}
}

func (c *LRUCache) Get(key string) (interface{}, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()

	item, ok := c.cache[key]
	if !ok || item.ExpireTime.Before(time.Now()) {
		return nil, false
	}

	c.evictList.MoveToFront(item.Value.(*list.Element))
	return item.Value, true
}

func (c *LRUCache) Put(key string, value interface{}, ttl time.Duration) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if item, ok := c.cache[key]; ok {
		c.evictList.Remove(item.Value.(*list.Element))
		delete(c.cache, key)
	} else if len(c.cache) >= c.capacity {
		lastElem := c.evictList.Back()
		delete(c.cache, lastElem.Value.(*CacheItem).Key)
		c.evictList.Remove(lastElem)
	}

	item := &CacheItem{
		Value:      value,
		ExpireTime: time.Now().Add(ttl),
	}
	itemValue := item.Value
	element := c.evictList.PushFront(itemValue)
	c.cache[key] = *item
}

func (c *LRUCache) StartEviction(interval time.Duration) {
	ticker := time.NewTicker(interval)
	go func() {
		for range ticker.C {
			c.mu.Lock()
			now := time.Now()
			for _, item := range c.cache {
				if item.ExpireTime.Before(now) {
					c.evictList.Remove(item.Value.(*list.Element))
					delete(c.cache, item.Key)
				}
			}
			c.mu.Unlock()
		}
	}()
}

func main() {
	cache := NewLRUCache(2)
	cache.Put("key1", "value1", 5*time.Second)
	cache.Put("key2", "value2", 5*time.Second)
	fmt.Println(cache.Get("key1")) // 輸出: value1 true

	cache.StartEviction(1 * time.Second)

	time.Sleep(6 * time.Second)
	fmt.Println(cache.Get("key1")) // 輸出: <nil> false
}

這兩種策略可以結(jié)合使用,以實(shí)現(xiàn)更高效的緩存失效處理。

向AI問一下細(xì)節(jié)

免責(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)容。

go
AI