缓存是高并发系统的基石,但缓存用不好会带来三大经典问题:穿透、击穿、雪崩。本文分析每个问题的成因与解决方案。

缓存穿透

问题

查询一个数据库中根本不存在的数据。每次请求都穿透缓存直达数据库,恶意攻击时数据库会被打垮。

解决方案

方案一:缓存空值

func GetUser(id int) *User {
    user := redis.Get("user:" + id)
    if user != nil {
        if user == NULL_CACHE { return nil }
        return user
    }
    user := db.QueryUser(id)
    if user == nil {
        redis.Set("user:" + id, NULL_CACHE, 60) // 缓存空值 60 秒
        return nil
    }
    redis.Set("user:" + id, user, 3600)
    return user
}

方案二:布隆过滤器

在缓存前加一层布隆过滤器,快速判断数据是否可能存在。不存在的请求直接拦截,不查数据库。

缓存击穿

问题

某个热点 Key 突然过期,瞬间大量并发请求同时落到数据库。

解决方案

互斥锁:只让一个请求去重建缓存,其他请求等待后重试。

func GetHotData(key string) string {
    data := redis.Get(key)
    if data != nil { return data }

    // 尝试获取锁
    if redis.SetNX("lock:"+key, "1", 10*time.Second) {
        defer redis.Del("lock:" + key)
        data := db.Query(key)        // 重建缓存
        redis.Set(key, data, 3600)
        return data
    }
    time.Sleep(100 * time.Millisecond)
    return GetHotData(key) // 重试
}

缓存雪崩

问题

大量 Key 同时过期,或缓存节点宕机,海量请求全部打到数据库。

解决方案

1. 随机过期时间:在基础过期时间上加随机偏移。

baseTTL := 3600
ttl := baseTTL + rand.Intn(300) // 3600~3900 秒随机
redis.Set(key, data, ttl)

2. 缓存高可用:部署 Redis 哨兵或集群,避免单点故障。

3. 服务降级:数据库扛不住时返回默认值或限流。

三者对比

问题数据特征影响范围核心方案
穿透数据不存在固定 Key布隆过滤器/缓存空值
击穿热点数据过期单个 Key互斥锁
雪崩大量 Key 同时过期大面积随机过期+高可用
生产建议:三个问题的防护层应该都加上——布隆过滤器在前拦截非法请求,热点 Key 用互斥锁重建,普通 Key 加随机过期时间。