溫馨提示×

溫馨提示×

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

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

Go HashMap緩存的清理與維護(hù)

發(fā)布時間:2024-11-08 20:45:44 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

Go中的HashMap緩存可以通過以下方法進(jìn)行清理和維護(hù):

  1. 設(shè)置過期時間:為HashMap中的每個鍵值對設(shè)置一個過期時間,當(dāng)超過這個時間時,自動清除該鍵值對。可以使用time.AfterFunc函數(shù)來實(shí)現(xiàn)這個功能。
package main

import (
	"fmt"
	"time"
)

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

type HashMapCache struct {
	items map[string]CacheItem
}

func NewHashMapCache() *HashMapCache {
	return &HashMapCache{
		items: make(map[string]CacheItem),
	}
}

func (c *HashMapCache) Set(key string, value interface{}, duration time.Duration) {
	expireTime := time.Now().Add(duration)
	c.items[key] = CacheItem{
		Value:      value,
		ExpireTime: expireTime,
	}
}

func (c *HashMapCache) Get(key string) (interface{}, bool) {
	item, ok := c.items[key]
	if !ok || time.Now().After(item.ExpireTime) {
		return nil, false
	}
	return item.Value, true
}

func (c *HashMapCache) Remove(key string) {
	delete(c.items, key)
}

func (c *HashMapCache) Clear() {
	c.items = make(map[string]CacheItem)
}

func main() {
	cache := NewHashMapCache()
	cache.Set("key1", "value1", 5*time.Second)
	cache.Set("key2", "value2", 10*time.Second)

	if value, ok := cache.Get("key1"); ok {
		fmt.Println("key1:", value)
	} else {
		fmt.Println("key1 not found or expired")
	}

	time.Sleep(6 * time.Second)

	if value, ok := cache.Get("key1"); ok {
		fmt.Println("key1:", value)
	} else {
		fmt.Println("key1 not found or expired")
	}

	cache.Remove("key1")

	if value, ok := cache.Get("key1"); ok {
		fmt.Println("key1:", value)
	} else {
		fmt.Println("key1 not found or expired")
	}
}
  1. 使用定時器:可以設(shè)置一個定時器,定期檢查HashMap中的鍵值對是否已經(jīng)過期,如果過期則清除??梢允褂?code>time.Ticker來實(shí)現(xiàn)這個功能。
package main

import (
	"fmt"
	"time"
)

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

type HashMapCache struct {
	items map[string]CacheItem
}

func NewHashMapCache() *HashMapCache {
	return &HashMapCache{
		items: make(map[string]CacheItem),
	}
}

func (c *HashMapCache) Set(key string, value interface{}, duration time.Duration) {
	expireTime := time.Now().Add(duration)
	c.items[key] = CacheItem{
		Value:      value,
		ExpireTime: expireTime,
	}
}

func (c *HashMapCache) Get(key string) (interface{}, bool) {
	item, ok := c.items[key]
	if !ok || time.Now().After(item.ExpireTime) {
		return nil, false
	}
	return item.Value, true
}

func (c *HashMapCache) Remove(key string) {
	delete(c.items, key)
}

func (c *HashMapCache) Clear() {
	c.items = make(map[string]CacheItem)
}

func (c *HashMapCache) StartCleanupTimer(duration time.Duration) {
	ticker := time.NewTicker(duration)
	go func() {
		for range ticker.C {
			c.Cleanup()
		}
	}()
}

func (c *HashMapCache) Cleanup() {
	now := time.Now()
	for key, item := range c.items {
		if now.After(item.ExpireTime) {
			c.Remove(key)
		}
	}
}

func main() {
	cache := NewHashMapCache()
	cache.Set("key1", "value1", 5*time.Second)
	cache.Set("key2", "value2", 10*time.Second)

	cache.StartCleanupTimer(2 * time.Second)

	time.Sleep(10 * time.Second)
	cache.StopCleanupTimer()
}
  1. 內(nèi)存限制:當(dāng)HashMap占用的內(nèi)存達(dá)到一定閾值時,可以自動清除部分過期或不再使用的鍵值對??梢允褂?code>sync.Pool來實(shí)現(xiàn)這個功能。
package main

import (
	"container/list"
	"fmt"
	"time"
)

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

type HashMapCache struct {
	items map[string]*list.Element
	evict  *list.List
}

func NewHashMapCache(maxSize int) *HashMapCache {
	return &HashMapCache{
		items: make(map[string]*list.Element),
		evict:  list.New(),
		maxSize: maxSize,
	}
}

func (c *HashMapCache) Set(key string, value interface{}, duration time.Duration) {
	if elem, ok := c.items[key]; ok {
		c.evict.MoveToFront(elem)
		elem.Value.(*CacheItem).Value = value
		elem.Value.(*CacheItem).ExpireTime = time.Now().Add(duration)
		return
	}

	if c.evict.Len() >= c.maxSize {
		lastElem := c.evict.Back()
		c.removeItem(lastElem)
	}

	item := &CacheItem{
		Value:      value,
		ExpireTime: time.Now().Add(duration),
	}

	elem := c.evict.PushFront(item)
	c.items[key] = elem
}

func (c *HashMapCache) Get(key string) (interface{}, bool) {
	if elem, ok := c.items[key]; ok {
		if time.Now().After(elem.Value.(*CacheItem).ExpireTime) {
			c.removeItem(elem)
			return nil, false
		}
		c.evict.MoveToFront(elem)
		return elem.Value.(*CacheItem).Value, true
	}
	return nil, false
}

func (c *HashMapCache) Remove(elem *list.Element) {
	delete(c.items, elem.Value.(*CacheItem).Key)
	c.evict.Remove(elem)
}

func (c *HashMapCache) Clear() {
	c.items = make(map[string]*list.Element)
	c.evict = list.New()
}

func main() {
	cache := NewHashMapCache(2)
	cache.Set("key1", "value1", 5*time.Second)
	cache.Set("key2", "value2", 10*time.Second)

	time.Sleep(6 * time.Second)
	cache.Set("key3", "value3", 15*time.Second)

	if value, ok := cache.Get("key1"); ok {
		fmt.Println("key1:", value)
	} else {
		fmt.Println("key1 not found or expired")
	}

	if value, ok := cache.Get("key2"); ok {
		fmt.Println("key2:", value)
	} else {
		fmt.Println("key2 not found or expired")
	}

	if value, ok := cache.Get("key3"); ok {
		fmt.Println("key3:", value)
	} else {
		fmt.Println("key3 not found or expired")
	}
}

這些方法可以根據(jù)實(shí)際需求進(jìn)行組合使用,以實(shí)現(xiàn)更高效的緩存清理和維護(hù)。

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

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

go
AI