Redis - 慢查询

前言

慢查询,大家可能已经接触到了MySQL的慢查询。我们配置一个时间,如果查询时间超过了我们设置的时间,我们就认为这是一个慢查询.

《Redis - 慢查询》 一条客户端命令的生命周期

如上图所示:Redis客户端一条命令执行分4个步骤:

  1. 发送命令
  2. 命令进入队列排队
  3. 执行命令
  4. 返回结果

慢查询统计的是第3步(执行命令)的时间。

参数配置

慢查询有两个参数需要配置:

  • [ ] slowlog-log-slower-than

    表示慢查询预设的超时阀值,单位是微妙(μs)
    1s = 1000ms = 1_000_000μs
    默认10000微秒,即10毫秒
    执行超过这个时间的命令将被记录到慢查询日志
    slowlog-log-slower-than = 0:表示记录所有命令。
    slowlog-log-slower-than < 0:表示不记录

  • [ ] slowlog-max-len

    表示慢查询日志的条数
    默认为 128
    Redis使用列表存储慢查询日志
    当已经记录了128条慢查询,现在又来一条,最早记录的那条将被踢出,最新一条入列

修改配置

  • 直接修改配置文件
  • config set 命令动态修改
# 设置记录所有命令
config set slowlog-log-slower-than 0
# 最多记录100条
config set slowlog-max-len 100
# 持久化到本地配置文件
config rewrite

慢查询日志操作

  • 查询
# 获取慢查询日志,n表示获取的条数
slowlog get [n]

当我们执行了查询命令之后,一条慢查询记录显示如下:

1) (integer) 0
2) (integer) 1527991482
3) (integer) 12
4) 1) "config"
   2) "set"
   3) "slowlog-log-slower-than"
   4) "0"

可以看到日志由4个属性组成:

1)日志的标识id
2)发生的时间戳
3)命令耗时
4)执行的命令和参数

  • 获取慢查询列表长度
slowlog len
  • 清空日志列表
# 如果慢查询设置的阀值是0,那么再查询len的时候为1。
slowlog reset

附录

操作GIF

《Redis - 慢查询》 redis-slowlog.gif

redis.conf慢查询的注释和配置

################################## SLOW LOG ###################################

# The Redis Slow Log is a system to log queries that exceeded a specified
# execution time. The execution time does not include the I/O operations
# like talking with the client, sending the reply and so forth,
# but just the time needed to actually execute the command (this is the only
# stage of command execution where the thread is blocked and can not serve
# other requests in the meantime).
#
# You can configure the slow log with two parameters: one tells Redis
# what is the execution time, in microseconds, to exceed in order for the
# command to get logged, and the other parameter is the length of the
# slow log. When a new command is logged the oldest one is removed from the
# queue of logged commands.

# The following time is expressed in microseconds, so 1000000 is equivalent
# to one second. Note that a negative number disables the slow log, while
# a value of zero forces the logging of every command.
slowlog-log-slower-than 10000

# There is no limit to this length. Just be aware that it will consume memory.
# You can reclaim memory used by the slow log with SLOWLOG RESET.
slowlog-max-len 128

    原文作者:番薯IT
    原文地址: https://www.jianshu.com/p/496d5704c85d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞