缓存战术手册:多级缓存与缓存预热/失效策略
Redis + 本地内存组合缓存,解决缓存穿透、击穿、雪崩,以及懒加载与主动预热。 · 难度:入门 · +10XP
多级缓存与失效策略
简单教程只教你 cache.set/cache.get,但高并发下需要多级缓存(本地 LRU + Redis + 数据库)。本课实现一个 CacheManager 类:先查本地内存(如 Django 的 locmem),再查 Redis,最后回源。同时解决缓存穿透(布隆过滤器)、击穿(互斥锁)、雪崩(随机过期时间)三大难题。还会介绍 Write-Through 和 Write-Behind 两种写入策略,以及基于消息队列的缓存预热。
class MultiLevelCache:
def get(self, key, default=None):
value = cache.get(key) # 本地缓存
if value is None:
value = redis.get(key)
if value is None:
value = get_from_db(key)
redis.set(key, value, timeout=300)
cache.set(key, value, timeout=60)
return value