在Golang面试中,实现一个并发安全且支持过期清理的缓存结构是常见的高频题目。这类问题不仅考察候选人对Go并发模型的理解,还考察对实际应用场景的把握能力。本文将详细解析如何设计并实现这样一个缓存系统,并提供完整可运行的代码示例。
+------------------+ +-----------------+
| Cache | | Item |
+------------------+ +-----------------+
| - items: map |1 * | - Value: interface{}
| - mu: RWMutex |---------| - Expiration: int64
| - cleanupInterval| +-----------------+
| - stopChan: chan |
+------------------+
结构说明:
Cache 结构体:
items
:存储缓存项的映射表mu
:读写锁,保证并发安全cleanupInterval
:清理过期项的间隔时间stopChan
:停止后台清理的信号通道Item 结构体:
Value
:存储的任意类型值Expiration
:过期时间戳(纳秒级) +-------------+
| Set操作 |
+------+------+
|
v
+------+ 获取写锁 +------+
| +----------> |
| 缓存 | | 缓存 |
| 状态 | | 状态 |
| <----------+ |
+------+ 设置值后释放锁 +------+
|
v
+-------------+
| Get操作 |
+------+------+
|
v
+------+ 获取读锁 +------+
| +----------> |
| 缓存 | | 缓存 |
| 状态 | | 状态 |
| <----------+ |
+------+ 读取值后释放锁 +------+
|
v
+-------------+
| 后台清理任务 |
+------+------+
|
v
+------+ 获取写锁 +------+
| +----------> |
| 缓存 | | 缓存 |
| 状态 | 删除过期项 | 状态 |
| <----------+ |
+------+ 释放锁 +------+
使用sync.RWMutex
实现读写分离:
func (c *Cache) Set(key string, value interface{}, ttl time.Duration) {
c.mu.Lock() // 写操作使用互斥锁
defer c.mu.Unlock()
// ...
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock() // 读操作使用读锁
defer c.mu.RUnlock()
// ...
}
清理策略特点:
func (c *Cache) startCleanup() {
ticker := time.NewTicker(c.cleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.cleanup() // 定期执行清理
case <-c.stopChan: // 接收停止信号
return
}
}
}
func (c *Cache) cleanup() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now().UnixNano()
for key, item := range c.items {
if item.Expiration > 0 && now > item.Expiration {
delete(c.items, key) // 删除过期项
}
}
}
使用纳秒级时间戳存储过期时间:
expiration := time.Now().Add(ttl).UnixNano()
func main() {
// 创建缓存,每10秒清理一次过期项
cache := cache.NewCache(10 * time.Second)
defer cache.Close() // 程序退出时关闭缓存
// 设置缓存项,5秒过期
cache.Set("key1", "value1", 5*time.Second)
cache.Set("key2", 42, 10*time.Second) // 整数
cache.Set("key3", struct{}{}, 0) // 永久有效
// 立即获取
if val, ok := cache.Get("key1"); ok {
fmt.Println("key1:", val) // 输出: key1: value1
}
// 6秒后获取
time.Sleep(6 * time.Second)
if _, ok := cache.Get("key1"); !ok {
fmt.Println("key1 expired") // 输出: key1 expired
}
// 获取永久项
if _, ok := cache.Get("key3"); ok {
fmt.Println("key3 still exists")
}
// 测试并发读写
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key := fmt.Sprintf("goroutine_%d", i)
cache.Set(key, i, time.Minute)
if val, ok := cache.Get(key); ok {
_ = val // 使用值
}
}(i)
}
wg.Wait()
fmt.Println("Concurrent test completed")
}
type ShardedCache struct {
shards []*Cache
}
func NewShardedCache(shardCount int, cleanupInterval time.Duration) *ShardedCache {
cache := &ShardedCache{
shards: make([]*Cache, shardCount),
}
for i := range cache.shards {
cache.shards[i] = NewCache(cleanupInterval)
}
return cache
}
func (sc *ShardedCache) getShard(key string) *Cache {
h := fnv.New32a()
h.Write([]byte(key))
return sc.shards[h.Sum32()%uint32(len(sc.shards))]
}
优势:
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
item, found := c.items[key]
c.mu.RUnlock()
if !found {
return nil, false
}
// 惰性检查过期
if time.Now().UnixNano() > item.Expiration {
c.mu.Lock()
delete(c.items, key) // 过期则删除
c.mu.Unlock()
return nil, false
}
return item.Value, true
}
优势:
type Cache struct {
items map[string]Item // 直接存储结构体而非指针
// ...
}
type Item struct {
Value interface{}
Expiration int64
}
优化点:
RWMutex允许并发读操作,在缓存这种读多写少的场景下,能显著提升性能。当有活跃的读锁时,写操作会被阻塞,但读操作可以并行执行。
type LRUCache struct {
cache map[string]*list.Element
list *list.List
capacity int
mu sync.Mutex
}
func (l *LRUCache) Get(key string) (interface{}, bool) {
l.mu.Lock()
defer l.mu.Unlock()
if elem, ok := l.cache[key]; ok {
l.list.MoveToFront(elem)
return elem.Value.(*Item).Value, true
}
return nil, false
}
func (l *LRUCache) Set(key string, value interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
if elem, ok := l.cache[key]; ok {
l.list.MoveToFront(elem)
elem.Value.(*Item).Value = value
return
}
if len(l.cache) >= l.capacity {
// 淘汰最久未使用
elem := l.list.Back()
delete(l.cache, elem.Value.(*Item).Key)
l.list.Remove(elem)
}
elem := l.list.PushFront(&Item{Key: key, Value: value})
l.cache[key] = elem
}
UnixNano()返回纳秒级时间戳,相比秒级时间戳:
实现一个并发安全且支持过期清理的缓存结构需要综合考虑:
本文实现的缓存结构满足面试题要求,并提供了多种优化思路。在实际应用中,可根据需求添加LRU淘汰、持久化、监控统计等功能。掌握这类并发数据结构的设计思想,对于深入理解Go语言并发模型和解决实际问题至关重要。
面试提示:在回答此类问题时,不仅要展示代码实现,更要解释设计决策背后的思考过程,特别是权衡不同方案时的考虑因素,这能体现你的工程思维深度。