Redis:慢查询分析与优化的技术指南

admin
5
2025-07-25

🔍 1、简述

Redis 慢查询是指执行时间超过预设阈值的命令请求。Redis 将所有执行时间超过 slowlog-log-slower-than 配置的请求记录在内存队列中,供开发者分析性能瓶颈。

慢查询的三个关键参数:

🔹 slowlog-log-slower-than:慢查询阈值(微秒)

🔹 slowlog-max-len:慢查询日志最大长度

🔹 slowlog entries:已记录的慢查询数量

image-e8yf.png


2、什么是 Redis 慢查询?

Redis 认为一条命令执行时间超过设定阈值(单位:微秒)就属于慢查询,会自动记录到慢查询日志中,供开发者排查。

2.1 相关配置项说明(redis.conf)

# 设置慢查询阈值(单位:微秒,10000μs = 10ms)
slowlog-log-slower-than 10000

# 最多保存的慢查询日志数量
slowlog-max-len 128

🔹 slowlog-log-slower-than:默认 10000(即超 10ms 会被记录),设置为 0 表示记录所有命令,设置为 -1 表示关闭。

🔹 slowlog-max-len:日志条数上限,超过时旧记录会被淘汰。

✅ 线上推荐设置:

slowlog-log-slower-than 10000
slowlog-max-len 1024

2.2 慢查询常用命令

命令 说明
SLOWLOG GET [n] 获取最近的 n 条慢查询记录
SLOWLOG LEN 查询当前慢查询日志数量
SLOWLOG RESET 清空慢查询日志(⚠️慎用)

示例:

127.0.0.1:6379> SLOWLOG GET 5

返回格式示例:

1) 1) (integer) 14               # 慢查询ID
   2) (integer) 1631234567       # 时间戳
   3) (integer) 12567            # 执行时间(微秒)
   4) 1) "keys"                  # 命令
      2) "user:*"                # 参数
   5) "127.0.0.1:58352"          # 客户端地址
   6) "db0"                      # 数据库编号

解释:

🔹 命令:HGETALL user:10000

🔹 执行时间:15.4ms(超过默认阈值 10ms 被记录)


3、实践样例:慢查询触发 & 分析

使用 Spring Boot + Redis 示例:

1️⃣ 模拟慢查询

// 模拟慢查询:向 List 中插入百万数据再读取
for (int i = 0; i < 1_000_000; i++) {
    redisTemplate.opsForList().rightPush("test:list", "value" + i);
}

// 慢命令:从列表中获取全部元素
List<String> all = redisTemplate.opsForList().range("test:list", 0, -1);

⚠️ LRANGE test:list 0 -1 会加载所有元素,容易成为慢查询。


2️⃣ 连接 Redis 手动查询慢日志

SLOWLOG GET 3
1) 1) (integer) 21
   2) (integer) 1688532340
   3) (integer) 27230
   4) 1) "LRANGE"
      2) "test:list"
      3) "0"
      4) "-1"

4、自动化监控方案

4.1 使用 redis-cli 定期检查

#!/bin/bash
# 慢查询监控脚本
THRESHOLD=10000  # 10毫秒
SLOWLOG_COUNT=$(redis-cli slowlog len)

if [ $SLOWLOG_COUNT -gt 0 ]; then
    redis-cli slowlog get | mail -s "Redis Slowlog Alert" admin@example.com
    redis-cli slowlog reset  # 清空日志
fi

4.2 Prometheus + Grafana 监控

配置 redis_exporter 采集指标:

metrics:
  - name: redis_slowlog_entries
    help: Total slowlog entries
    key: 'slowlog.len'
    type: gauge

4.3 ELK 日志分析

通过 Filebeat 采集 Redis 慢日志,在 Logstash 中解析日志:

filter {
  grok {
    match => { "message" => "\[%{INT:duration}\] %{GREEDYDATA:command}" }
  }
}

4.4 监控与报警推荐

工具 功能
RedisInsight Redis Labs 官方 GUI,可查看慢日志
Grafana + Prometheus 可接入 Redis exporter 监控慢命令执行率
ELK / Loki 通过日志采集慢查询输出,实时告警
自定义告警脚本 定期轮询 SLOWLOG GET 并发送邮件/钉钉告警

5、总结

Redis 慢查询分析是性能优化的关键环节,通过合理配置和系统化监控,可以显著提升 Redis 服务稳定性。关键要点:

✅ 避免大 Key(单个 List、Hash、Set 中包含上百万元素)

✅ 避免长命令(如一次性读取所有元素)

✅ 分批分页操作(如使用 LRANGE list 0 99 + 滚动分页)

✅ 使用 SCAN 命令代替 KEYS / SMEMBERS 等全量命令

✅ 合理设置慢查询阈值和日志长度

✅ 使用 Lua 脚本合并多次调用,减少网络往返时间(RTT)

通过本文介绍的工具和方法,开发者可以构建完整的 Redis 性能监控体系,快速定位和解决性能瓶颈。

动物装饰