當Redis的內存已經快滿的時候,我們能做什么呢?
最直接的方法就是分析一下Redis內存的構成,看是哪些鍵比較大,或者比較多,然后考慮一下對應的功能能不能優化,例如減少超時時間,例如不必要的數據不用放緩存,例如有些鍵已經沒有用了,但是沒有及時刪除,也沒有超時時間
分析Redis內存的構成,常用的是用分析工具rdbtools,這個工具可以導出redis的所有key,以及它占用的內存大小。
一、安裝
pip install python-lzf
pip install rdbtools
能執行rdb命令,表示安裝成功
二、使用
(vsing_backend) [www@NingBo_10_1_33_26 data]$ rdb --help
Usage: rdb [options] /path/to/dump.rdb
Example : rdb --command json -k "user.*" /var/redis/6379/dump.rdb
Options:
-h, --help show this help message and exit
-c FILE, --command=FILE
Command to execute. Valid commands are json, diff,
justkeys, justkeyvals, memory and protocol
-f FILE, --file=FILE Output file
-n DBS, --db=DBS Database Number. Multiple databases can be provided.
If not specified, all databases will be included.
-k KEYS, --key=KEYS Keys to export. This can be a regular expression
-o NOT_KEYS, --not-key=NOT_KEYS
Keys Not to export. This can be a regular expression
-t TYPES, --type=TYPES
Data types to include. Possible values are string,
hash, set, sortedset, list. Multiple typees can be
provided. If not specified, all
data types will be returned
-b BYTES, --bytes=BYTES
Limit memory output to keys greater to or equal to
this value (in bytes)
-l LARGEST, --largest=LARGEST
Limit memory output to only the top N keys (by size)
-e ESCAPE, --escape=ESCAPE
Escape strings to encoding: raw (default), print,
utf8, or base64.
三、基本命令
分析rdb文件,生成內存使用報告:
rdb -c memory -k "test*" dump.rdb > /data1/kevinlu/a.csv
- -c memory
- -k 表示只統計那些keys,支持通配符
- dump.rdb redis的RDB文件,通過bgsave生成
- 把結果導出到/data1/kevinlu/a.csv文件
注意:
- 報告中的內存使用量,單位是字節。報告中的內存使用量只是近似值。實際的內存使用量會比報告的使用量稍大,大概1.5倍到1.7倍左右。(測試的時候,Redis info命令的內存占用是8G,dump.rdb文件是2.7G,報告的內存使用總量是5G)
四、redis RDB文件生成
- 通過命令bgsave來生成,這樣不影響線上業務
- 生成前需要備份原有的dump.rdb,不然會覆蓋
- 生成前注意看機器內存,例如如果Redis內存已經到7G,那bgsave生成的過程中,redis進程需要再占7G內存,要注意內存夠不夠
- 注意硬盤夠不夠,不過這個一般是夠的