如何排查Redis单个Key命中率骤降?
问题现象
Redis整体命中率98%,但监控发现特定Key(如user:1000:profile
)的命中率从99%骤降至40%,引发服务延迟上升。
排查步骤
1. 确认现象与定位Key
// 通过Redis监控工具获取Key指标
public void monitorKey(String key) {Jedis jedis = new Jedis("localhost");// 使用Redis命令分析Key访问模式System.out.println("Key访问统计: " + jedis.objectEncoding(key));System.out.println("Key剩余TTL: " + jedis.ttl(key) + "秒");
}
- 使用
redis-cli --hotkeys
或monitor
命令确认Key访问频率 - 检查监控系统(如Grafana)观察命中率下降时间点
2. 检查业务变更
// 检查新上线代码:缓存读写逻辑是否变化
@Service
public class UserService {// 变更前代码:正常缓存读取@Cacheable(value = "userProfile", key = "#userId")public User getProfile(Long userId) { /* 查数据库 */ }// 变更后问题代码:错误覆盖了缓存Keypublic void updateProfile(Long userId) {userDao.update(userId);// 错误:未清除旧缓存,直接写入新KeyredisTemplate.opsForValue().set("user_profile_" + userId, newData); }
}
- 排查点:
- 是否新增绕过缓存的直接DB查询?
- Key生成规则是否改变(如
user:{id}
→user_profile_{id}
)? - 缓存清理逻辑是否遗漏(如@CacheEvict注解缺失)
3. 分析缓存失效策略
// 检查TTL设置:确认是否设置过短
@Configuration
public class RedisConfig {@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory factory) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()// 问题点:全局设置10分钟TTL.entryTtl(Duration.ofMinutes(10)); return RedisCacheManager.builder(factory).cacheDefaults(config).build();}
}
- 关键问题:
- TTL设置不合理:热点Key过期时间过短
- 批量失效:定时任务导致关联Key集中清除
- 内存淘汰策略:检查
maxmemory-policy
是否主动删除Key
4. 验证数据一致性
// 典型缓存不一致场景:先更库后删缓存失败
public void updateUser(Long userId) {// 步骤1:更新数据库userDao.update(userId);// 步骤2:删除缓存(可能失败)try {redisTemplate.delete("user:" + userId);} catch (Exception e) {// 未处理异常导致缓存未删除!logger.error("缓存删除失败", e);}
}
- 一致性陷阱:
- 缓存穿透:恶意请求不存在的Key(如
user:-1
) - 缓存击穿:热点Key失效瞬间大量请求穿透
- 更新顺序:DB更新成功但缓存删除失败
- 缓存穿透:恶意请求不存在的Key(如
针对性解决方案
方案1:缓存穿透 → 空值缓存
public User getProfile(Long userId) {String key = "user:" + userId;User user = redisTemplate.opsForValue().get(key);if (user == null) {user = userDao.findById(userId);// 缓存空值防止穿透redisTemplate.opsForValue().set(key, user != null ? user : "NULL", 5, TimeUnit.MINUTES);}return "NULL".equals(user) ? null : user;
}
方案2:缓存击穿 → 互斥锁
public User getProfileWithLock(Long userId) {String key = "user:" + userId;User user = redisTemplate.opsForValue().get(key);if (user == null) {String lockKey = "lock:" + key;if (redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {try {user = userDao.findById(userId); // 查DBredisTemplate.opsForValue().set(key, user, 1, TimeUnit.HOURS);} finally {redisTemplate.delete(lockKey); // 释放锁}} else {// 其他线程等待重试Thread.sleep(50);return getProfileWithLock(userId);}}return user;
}
方案3:一致性保障 → 双删策略
public void updateUser(Long userId) {// 1. 先删缓存redisTemplate.delete("user:" + userId); // 2. 更新数据库userDao.update(userId); // 3. 延时二次删除(应对主从延迟)executor.schedule(() -> {redisTemplate.delete("user:" + userId);}, 1, TimeUnit.SECONDS);
}
预防措施
- 监控预警:
- 对核心Key设置命中率阈值告警(如<90%触发)
- 日志记录缓存删除失败操作
- 架构优化:
- 使用
Redisson
实现分布式锁 - 采用
Caffeine
实现本地二级缓存
- 使用
- 策略配置:
# Redis配置调整 config set maxmemory-policy allkeys-lru # 内存不足时LRU淘汰 config set notify-keyspace-events Ex # 订阅Key过期事件
经验总结:80%的命中率下降源于业务变更和失效策略不当。通过代码审查 + 实时监控 + 防御性编程,可快速定位并解决此类问题。