缓存是高并发系统的基石,但缓存用不好会带来三大经典问题:穿透、击穿、雪崩。本文分析每个问题的成因与解决方案。
查询一个数据库中根本不存在的数据。每次请求都穿透缓存直达数据库,恶意攻击时数据库会被打垮。
方案一:缓存空值
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 加随机过期时间。