前言
前些日子遇到一次生产环境下的redis热key,大key问题,导致用户疯狂投诉,汗流浃背了,排查过程倒是不难,不过挡不住是临近下班的时候。。。
事故背景
影响线上:
crm.prod.baidu.com
crmprod.baidu.com
idg-console.baidu.com
erp-uat.baidu.com
idgsvc.baidu.com
某日,公司 某 系统的用户突然反映系统响应变得异常缓慢。经初步排查,发现问题集中在 Redis 的访问上。开始排查(加班)
初始排查
首先,我们登录到生产环境的 Redis 实例,使用 info
命令获取 Redis 的基本信息,并重点关注内存使用情况、命令执行频率等指标。
redis-cli info
输出的部分信息如下:
# Memory
used_memory:8589934592
used_memory_human:8.00G
used_memory_rss:10737418240
used_memory_peak:10737418240
used_memory_peak_human:10.00G
total_system_memory:17179869184
total_system_memory_human:16.00G
used_memory_lua:37888
used_memory_lua_human:37.00K
从以上信息可以看出,Redis 当前的内存使用量已经达到 8GB,且内存峰值达到了 10GB,这显然是一个不正常的情况。接下来,我们需要进一步确认是否存在热 Key 和大 Key 的问题。
确认热 Key 和大 Key
热 Key 排查
我们使用 redis-cli
提供的 monitor
命令来实时监控 Redis 的命令执行情况:
redis-cli monitor
通过观察一段时间的输出,我们发现某些 Key 的访问频率特别高。例如:
1563199497.225609 [0 127.0.0.1:6379] "GET" "user:1234:profile"
1563199497.225615 [0 127.0.0.1:6379] "GET" "user:1234:profile"
1563199497.225620 [0 127.0.0.1:6379] "GET" "user:1234:profile"
通过分析,我们确认 user:1234:profile
是一个热 Key。接下来,我们还需要确认是否存在大 Key。
大 Key 排查
我们使用 redis-cli
提供的 --bigkeys
选项来扫描 Redis 实例中的大 Key:
redis-cli --bigkeys
输出的部分信息如下:
# Scanning the entire keyspace to find biggest keys as well as average sizes per type.
[00.00%] Biggest hash found so far 'user:1234:profile' with 512 fields
[00.00%] Biggest list found so far 'user:messages' with 1024 items
[00.00%] Biggest string found so far 'session:token:abcd1234' with 2048 bytes
从以上信息可以看出,user:1234:profile
不仅是一个热 Key,还是一个大 Key。这可能是引发线上事故的主要原因。
分析和定位问题
我们需要进一步分析代码,确认在什么场景下会频繁访问 user:1234:profile
。通过查看相关代码,我们找到了以下部分:
public class UserService {
private static final String USER_PROFILE_KEY = "user:%d:profile";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public UserProfile getUserProfile(int userId) {
String key = String.format(USER_PROFILE_KEY, userId);
UserProfile profile = (UserProfile) redisTemplate.opsForValue().get(key);
if (profile == null) {
profile = loadUserProfileFromDB(userId);
redisTemplate.opsForValue().set(key, profile);
}
return profile;
}
private UserProfile loadUserProfileFromDB(int userId) {
// 从数据库加载用户信息
// ...
}
}
从代码中可以看出,每次访问用户的个人资料时,都会先从 Redis 中读取。如果 Redis 中没有数据,再从数据库中加载并写入 Redis。由于 user:1234:profile
是一个大 Key,频繁的读写操作带来了巨大的性能负担。