Redis 缓存实战:从入门到避免缓存雪崩
Redis Caching in Practice — From Basics to Preventing Cache Avalanche
| iDev Team | 2026-08-13T09:46:28
缓存能让接口响应从 200ms 降到 5ms,但用不好会引发缓存穿透、击穿、雪崩。本文教你正确姿势。
Caching can reduce API response from 200ms to 5ms, but misuse leads to cache penetration, breakdown, and avalanche. Learn the right approach.
什么时候该用缓存读多写少、数据变化不频繁、对实时性要求不高的场景。典型例子:新闻列表、分类数据、配置信息、用户简介。基本用法:Spring Boot + Redis引入 spring-boot-starter-data-redis,配置 Redis 连接,用 @Cacheable 注解标记方法,Spring 自动帮你缓存返回值。第一次查数据库,后续直接走 Redis,响应时间从 200ms 降到 5ms。三大经典问题缓存穿透查一个不存在的数据,缓存没有,每次都打到数据库。解决:缓存空值(设短过期时间)或布隆过滤器。缓存击穿一个热点 key 过期的瞬间,大量请求同时打到数据库。解决:互斥锁(只让一个请求去查数据库,其他等待)或设置热点 key 永不过期。缓存雪崩大量 key 在同一时间过期,数据库瞬间承受巨大压力。解决:过期时间加随机偏移(比如 30 分钟 ± 5 分钟),避免集中过期。过期策略设计新闻列表:缓存 5 分钟(内容更新不频繁)分类数据:缓存 1 小时(几乎不变)用户 session:缓存 24 小时(跟 JWT 对齐)首页数据:缓存 1 分钟(实时性要求高)
When to Use CachingHigh-read, low-write scenarios with infrequently changing data and relaxed real-time requirements. Examples: news lists, category data, configuration, user profiles.Basic Usage: Spring Boot + RedisAdd spring-boot-starter-data-redis, configure Redis connection, annotate methods with @Cacheable. Spring automatically caches return values. First call hits the database; subsequent calls go straight to Redis — response time drops from 200ms to 5ms.Three Classic ProblemsCache PenetrationQuerying non-existent data: cache has nothing, every request hits the database. Fix: cache null values (with short TTL) or use Bloom filters.Cache BreakdownA hot key expires, and thousands of requests simultaneously hit the database. Fix: mutex lock (only one request queries DB, others wait) or set hot keys to never expire.Cache AvalancheMany keys expire at the same time, overwhelming the database. Fix: add random offset to expiration times (e.g., 30 minutes ± 5 minutes) to prevent synchronized expiration.TTL Strategy DesignNews lists: 5-minute cache (content updates infrequently)Category data: 1-hour cache (rarely changes)User sessions: 24-hour cache (aligned with JWT)Homepage data: 1-minute cache (higher real-time requirement)