# 5.5 慢查询实战分析

## 5.5.1 慢查询相关的配置参数

* `slowlog-log-slower-than`:单位为微秒.超过该参数指定时长的查询会记录到日志中
* `slowlog-max-len`:在慢查询日志中可以记录的日志条数.当慢查询日志的数量已经到达该参数时,每有一条新的慢查询日志写入,就会有最老的一条日志被删除

例:设置慢查询的时长和慢查询日志的条数

```
127.0.0.1:6379> CONFIG SET slowlog-log-slower-than 1
OK
127.0.0.1:6379> CONFIG SET slowlog-max-len 100
OK
127.0.0.1:6379> CONFIG REWRITE
OK
```

此时配置文件内容如下:

```
# Generated by CONFIG REWRITE
slowlog-max-len 100
slowlog-log-slower-than 1
save 3600 1
save 300 100
save 60 10000
user default on nopass ~* &* +@all
dir "/redis-6.2.13"
```

## 5.5.2 用`SLOWLOG GET`命令观察慢查询

* `SLOWLOG GET`:返回所有的慢查询日志

```
127.0.0.1:6379> SET name Peter
OK
127.0.0.1:6379> GET name
"Peter"
```

```
127.0.0.1:6379> SLOWLOG GET
1) 1) (integer) 4
   2) (integer) 1692022815
   3) (integer) 3
   4) 1) "GET"
      2) "name"
   5) "127.0.0.1:57267"
   6) ""
2) 1) (integer) 3
   2) (integer) 1692022811
   3) (integer) 18
   4) 1) "SET"
      2) "name"
      3) "Peter"
   5) "127.0.0.1:57267"
   6) ""
3) 1) (integer) 2
   2) (integer) 1692022564
   3) (integer) 6865
   4) 1) "CONFIG"
      2) "REWRITE"
   5) "127.0.0.1:57267"
   6) ""
4) 1) (integer) 1
   2) (integer) 1692022560
   3) (integer) 5
   4) 1) "CONFIG"
      2) "SET"
      3) "slowlog-max-len"
      4) "100"
   5) "127.0.0.1:57267"
   6) ""
5) 1) (integer) 0
   2) (integer) 1692022556
   3) (integer) 13
   4) 1) "CONFIG"
      2) "SET"
      3) "slowlog-log-slower-than"
      4) "1"
   5) "127.0.0.1:57267"
   6) ""
```

我们以`GET name`命令的慢查询日志为例:

* `1) (integer) 4`:表示慢查询日志ID
* `2) (integer) 1692022815`:命令运行时的时间戳
* `3) (integer) 3`:命令运行的时长.单位为微秒
* `4) 1) "GET" 2) "name"`:一个数组.其中第一个元素是执行的命令,后续的元素是命令的参数
* `5) "127.0.0.1:57267"`:客户端地址和端口
* `6) ""`:客户端名称

## 5.5.3 慢查询相关命令

* `SLOWLOG GET n`:查看指定最新的n条慢查询日志

```
127.0.0.1:6379> SLOWLOG GET 1
1) 1) (integer) 5
   2) (integer) 1692022854
   3) (integer) 16
   4) 1) "SLOWLOG"
      2) "GET"
   5) "127.0.0.1:57267"
   6) ""
```

* `SLOWLOG LEN`:获取慢查询日志的长度

```
127.0.0.1:6379> SLOWLOG LEN
(integer) 9
```

* `SLOWLOG RESET`:清空慢查询日志

```
127.0.0.1:6379> SLOWLOG RESET
OK
127.0.0.1:6379> SLOWLOG LEN
(integer) 1
```

注:此处有1条慢查询日志是因为慢查询阈值设置的太低,导致`SLOWLOG LEN`也成为了慢查询


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://redis.sai.show/di-5-zhang-redis-shu-ju-ku-cao-zuo-shi-zhan/5.5-man-cha-xun-shi-zhan-fen-xi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
