答案:golang中可通过sync.map实现并发安全缓存,结合TTL过期机制和定时清理防止内存泄漏,并用LRU策略控制容量;核心是利用sync.Mutex保护list与map协同操作,确保高效读写与内存管理。

在高并发场景下,缓存是提升系统性能的关键组件。golang凭借其轻量级的goroutine和丰富的并发原语,非常适合构建高效的并发缓存系统。一个实用的缓存不仅要支持快速读写,还需处理同步问题并实现合理的淘汰策略。
使用 sync.Map 实现线程安全的缓存
Go 的内置 map 不是并发安全的,直接在多个 goroutine 中读写会引发竞态问题。sync.Map 是专为并发场景设计的映射类型,适合读多写少的缓存场景。
它无需额外加锁,即可安全地在多个协程中使用。以下是一个基于 sync.Map 的简单内存缓存实现:
type Cache struct { data *sync.Map } func NewCache() *Cache { return &Cache{data: &sync.Map{}} } func (c *Cache) Set(key string, value interface{}) { c.data.Store(key, value) } func (c *Cache) Get(key string) (interface{}, bool) { return c.data.Load(key) } func (c *Cache) Delete(key string) { c.data.Delete(key) }
这个结构足够轻便,适用于临时数据存储,但缺乏过期机制和容量控制。
立即学习“go语言免费学习笔记(深入)”;
添加过期时间与定时清理
缓存若不设置过期时间,容易导致内存泄漏或数据陈旧。可以通过记录过期时间戳,并配合后台 goroutine 定期清理来实现 TTL(Time To Live)功能。
type Item struct { Value interface{} ExpireAt int64 // unix 时间戳 } func (item *Item) IsExpired() bool { return time.Now().Unix() > item.ExpireAt }
在 Get 时判断是否过期,若已过期则删除并返回未命中:
func (c *Cache) Get(key string) (interface{}, bool) { if val, ok := c.data.Load(key); ok { item := val.(*Item) if item.IsExpired() { c.data.Delete(key) return nil, false } return item.Value, true } return nil, false } </font>
同时启动一个异步任务定期扫描并清除过期项:
func (c *Cache) StartEvictionGC(interval time.Duration) { ticker := time.NewTicker(interval) go func() { for range ticker.C { now := time.Now().Unix() c.data.Range(func(key, value interface{}) bool { item := value.(*Item) if now > item.ExpireAt { c.data.Delete(key) } return true }) } }() }
实现 LRU 淘汰策略控制内存增长
sync.Map 不支持按访问顺序管理元素,难以实现 LRU(Least Recently Used)。此时可结合 container/list 和 map 手动实现一个并发安全的 LRU 缓存。
核心思路是用双向链表维护访问顺序,哈希表实现 O(1) 查找。最近访问的节点移到链表头部,当缓存满时从尾部淘汰最久未使用的节点。
为保证并发安全,需使用 sync.Mutex 对整个操作加锁:
type LRUCache struct { mu sync.Mutex cache map[string]*list.Element list *list.List capacity int } type entry struct { key string value interface{} }
Set 操作需判断是否存在,存在则更新并移至队首;否则插入新节点,超出容量时淘汰尾节点:
func (c *LRUCache) Set(key string, value interface{}) { c.mu.Lock() defer c.mu.Unlock() if e, ok := c.cache[key]; ok { c.list.MoveToFront(e) e.Value.(*entry).value = value return } e := c.list.PushFront(&entry{key: key, value: value}) c.cache[key] = e if c.list.Len() > c.capacity { last := c.list.Back() if last != nil { c.list.Remove(last) delete(c.cache, last.Value.(*entry).key) } } }
Get 操作同样需要加锁,并将命中的节点移到前面以更新热度:
func (c *LRUCache) Get(key string) (interface{}, bool) { c.mu.Lock() defer c.mu.Unlock() if e, ok := c.cache[key]; ok { c.list.MoveToFront(e) return e.Value.(*entry).value, true } return nil, false } </font>
基本上就这些。通过组合 sync.Map、TTL 控制和 LRU 策略,可以在 Golang 中构建出满足不同需求的并发缓存系统。关键是根据业务权衡读写性能、内存占用和数据一致性。不复杂但容易忽略细节。