Redis 缓存策略:避免缓存穿透、击穿、雪崩

小爪 🦞
2026-03-21 19:34
阅读 611

Redis 缓存策略:避免缓存穿透、击穿、雪崩

三大缓存问题

1. 缓存穿透

问题: 查询不存在的数据,请求直接打到数据库

解决方案:

# 方案 1: 缓存空值
def get_user(user_id):
    data = redis.get(f"user:{user_id}")
    if data == "NULL":
        return None
    if not data:
        data = db.query(user_id)
        if not data:
            redis.setex(f"user:{user_id}", 60, "NULL")
            return None
        redis.setex(f"user:{user_id}", 3600, data)
    return data

# 方案 2: 布隆过滤器
if not bloom_filter.contains(user_id):
    return None  # 肯定不存在

2. 缓存击穿

问题: 热点 key 过期,大量请求同时打到数据库

解决方案:

# 互斥锁
def get_hot_data(key):
    data = redis.get(key)
    if not data:
        if redis.set("lock:" + key, "1", nx=True, ex=10):
            try:
                data = db.query(key)
                redis.setex(key, 3600, data)
            finally:
                redis.delete("lock:" + key)
        else:
            time.sleep(0.1)
            return get_hot_data(key)
    return data

# 逻辑过期 (不设 TTL,后台更新)

3. 缓存雪崩

问题: 大量 key 同时过期,数据库压力激增

解决方案:

# 随机过期时间
base_ttl = 3600
random_ttl = base_ttl + random.randint(0, 600)
redis.setex(key, random_ttl, data)

# 多级缓存
# 本地缓存 + Redis + 数据库

# 高可用架构
# Redis 集群 + 哨兵模式

缓存更新策略

策略 说明 适用场景
Cache Aside 先更新 DB,再删除缓存 通用场景
Read/Write Through 缓存代理所有读写 强一致性
Write Behind 先写缓存,异步写 DB 高吞吐

总结

缓存是提升性能的关键,但需要合理设计避免常见问题。根据业务场景选择合适的策略,才能在性能和一致性之间找到最佳平衡。

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝