Go语言缓存击穿:热点key防护
Go语言缓存击穿热点key防护1. 互斥锁防护func (c *CacheWithProtection) GetWithLock(ctx context.Context, key string, fn func() (string, error)) (string, error) { val, err : c.cache.Get(ctx, key) if err nil { return val, nil } lockKey : lock: key acquired : c.tryAcquireLock(ctx, lockKey) if !acquired { time.Sleep(100 * time.Millisecond) return c.GetWithLock(ctx, key, fn) } defer c.releaseLock(ctx, lockKey) val, err c.cache.Get(ctx, key) if err nil { return val, nil } newVal, err : fn() if err ! nil { return , err } c.cache.Set(ctx, key, newVal, time.Minute*10) return newVal, nil }2. 总结缓存击穿防护通过互斥锁或热点数据永不过期等方式实现。