在Go語言中,可以使用`sync.Map`或者`map`來實(shí)現(xiàn)本地緩存。
1. 使用`sync.Map`實(shí)現(xiàn)本地緩存:
package main import ( "sync" "time" ) type Cache struct { data sync.Map } func (c *Cache) Get(key string) (interface{}, bool) { value, ok := c.data.Load(key) if ok { return value, true } return nil, false } func (c *Cache) Set(key string, value interface{}) { c.data.Store(key, value) } func (c *Cache) Delete(key string) { c.data.Delete(key) } func main() { cache := &Cache{} cache.Set("key1", "value1") cache.Set("key2", "value2") value, ok := cache.Get("key1") if ok { println(value.(string)) // 輸出:value1 } cache.Delete("key2") value, ok = cache.Get("key2") if !ok { println("key2 not found") // 輸出:key2 not found } }
2. 使用`map`實(shí)現(xiàn)本地緩存:
package main import "time" type Cache struct { data map[string]interface{} expiry map[string]time.Time } func (c *Cache) Get(key string) (interface{}, bool) { value, ok := c.data[key] if ok { expiryTime := c.expiry[key] if expiryTime.After(time.Now()) { return value, true } else { delete(c.data, key) delete(c.expiry, key) return nil, false } } return nil, false } func (c *Cache) Set(key string, value interface{}, expiry time.Duration) { c.data[key] = value c.expiry[key] = time.Now().Add(expiry) } func (c *Cache) Delete(key string) { delete(c.data, key) delete(c.expiry, key) } func main() { cache := &Cache{ data: make(map[string]interface{}), expiry: make(map[string]time.Time), } cache.Set("key1", "value1", time.Second*10) cache.Set("key2", "value2", time.Second*20) value, ok := cache.Get("key1") if ok { println(value.(string)) // 輸出:value1 } time.Sleep(time.Second * 15) value, ok = cache.Get("key1") if !ok { println("key1 not found") // 輸出:key1 not found } }
以上是兩種常見的在Go語言中實(shí)現(xiàn)本地緩存的方法,選擇使用哪種取決于你對(duì)并發(fā)安全性和性能的需求。