Redis 缓存策略最佳实践
常见缓存模式
Cache-Aside(旁路缓存) — 最常用:
async function getPost(slug: string) {
const cached = await redis.get(`post:${slug}`);
if (cached) return JSON.parse(cached);
const post = await db.post.findUnique({ where: { slug } });
if (post) {
await redis.setex(`post:${slug}`, 3600, JSON.stringify(post));
}
return post;
}
Write-Through — 写入时同步更新缓存,适合读多写少场景。
Write-Behind — 异步批量写入,适合高写入频率,但有数据丢失风险。
三大缓存问题
缓存穿透:查询不存在的 key,请求直达数据库。 解决:布隆过滤器(Bloom Filter)预判 key 是否存在;或缓存空值。
缓存击穿:热点 key 失效瞬间,大量请求同时打到数据库。 解决:互斥锁(只允许一个请求重建缓存);或永不过期 + 后台定时刷新。
缓存雪崩:大量 key 同时失效。 解决:过期时间加随机抖动:
const ttl = 3600 + Math.floor(Math.random() * 600); // 3600 ± 10min
await redis.setex(key, ttl, value);
Key 命名规范
<业务>:<实体>:<ID>
post:detail:42
user:profile:1001
feed:home:1001:page:2
总结
缓存不是数据库的备份,而是热点数据的加速层。合理设置过期时间、做好缓存失效策略,是避免缓存问题的关键。不要让业务逻辑依赖缓存的一致性——数据库永远是 source of truth。