在Go语言中,可以使用`sync.Map`或者`map`来实现本地缓存。
1. 使用`sync.Map`实现本地缓存:
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`实现本地缓存:
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语言中实现本地缓存的方法,选择使用哪种取决于你对并发安全性和性能的需求。