面试题答案
一键面试实现思路
- 读取Redis慢查询日志文件。不同操作系统和Redis配置下,日志文件位置可能不同,一般在Redis配置文件中通过
slowlog-log-file
配置。 - 逐行解析日志内容,日志每行格式大致为
[编号] [时间戳] [执行时间(微秒)] [命令及参数]
。 - 针对每一行日志,提取执行时间和命令部分,判断执行时间是否大于100微秒且命令是否为SET。
- 符合条件的记录输出或存储以便后续分析。
代码示例(Python)
import os
slowlog_file_path = '/path/to/redis_slowlog.log' # 根据实际情况修改
with open(slowlog_file_path, 'r') as f:
for line in f.readlines():
parts = line.split(' ')
execution_time = int(parts[2])
command = parts[3]
if execution_time > 100 and command == 'SET':
print(line.strip())