Go语言缓存雪崩:防止缓存失效

Go语言缓存雪崩:防止缓存失效 Go语言缓存雪崩防止缓存失效1. 雪崩防护type CacheWithProtection struct { cache *RedisCache mu sync.Mutex locks map[string]*sync.Mutex } func NewCacheWithProtection(cache *RedisCache) *CacheWithProtection { return CacheWithProtection{ cache: cache, locks: make(map[string]*sync.Mutex), } } func (c *CacheWithProtection) GetOrSet(ctx context.Context, key string, fn func() (string, error)) (string, error) { val, err : c.cache.Get(ctx, key) if err nil { return val, nil } c.mu.Lock() if _, ok : c.locks[key]; !ok { c.locks[key] sync.Mutex{} } c.mu.Unlock() c.locks[key].Lock() defer c.locks[key].Unlock() 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*5) return newVal, nil }2. 总结缓存雪崩防护需要从缓存过期策略、分布式锁等多个角度综合考虑。