1. 程式人生 > 實用技巧 >Redis 分析工具 redis-rdb-tools

Redis 分析工具 redis-rdb-tools

redis 是基於記憶體的KV資料庫,記憶體作為儲存介質,關注記憶體的使用情況是一個重要的指標。解析記憶體有兩種方法,一個是通過scan遍歷所有key,二是對rdb檔案進行分析.

rdb 是rdb-tools工具包其中之一的工具,也是解析dump.rdb檔案的工具.

1、生成所有資料庫和鍵中資料的記憶體報告
2、將轉儲檔案轉換為JSON
3、使用標準差異工具比較兩個轉儲檔案

rdbtools工具包括了3個可執行檔案:

1、rdb 解析整個rdb檔案
2、redis-memory-for-key 解析server裡的單個key
3、redis-profiler 解析rdb檔案成html格式

原始碼安裝redis-rdb-tools:

git clone https://github.com/sripathikrishnan/redis-rdb-tools

cd redis-rdb-tools

python setup.py install

安裝 python-lzf :加快解析速度

pip install python-lzf

PyPI安裝(推薦)

pip install rdbtools python-lzf

引數解析:

[root@hankyoon ~]# rdb --help
usage: usage: rdb [options] /path/to/dump.rdb

Example : rdb 
--command json -k "user.*" /var/redis/6379/dump.rdb positional arguments: dump_file RDB Dump file to process optional arguments: -h, --help show this help message and exit -c CMD, --command CMD 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 {raw,print,utf8,base64}, --escape {raw,print,utf8,base64} Escape strings to encoding: raw (default), print, utf8, or base64. -x, --no-expire With protocol command, remove expiry from all keys -a N, --amend-expire N With protocol command, add N seconds to key expiry time

轉儲的json:

[root@hankyoon]# rdb --command json dump-5001.rdb

[{
"name":"yoon",
"name1":"hank",
"name2":"hankyoon"}]

正則表示式匹配key,並且列印鍵和值:

[root@10-0-10-30 yoon]# rdb --command justkeyvals --key "name.*" dump-5001.rdb

name yoon,
name1 hank,
name2 hankyoon

僅處理資料庫2中hash型別的a開頭的key:

[root@hankyoon ]# rdb -c json --db 2 --type hash --key "a.*" dump-5001.rdb

[{},{
"aroma":{"pungent":"vinegar","putrid":"rotten eggs","floral":"roses"}}]

dump檔案轉換為JSON:
輸出是UTF-8編碼的JSON。 預設情況下,回撥嘗試使用UTF-8解析RDB資料,並使用\U表示符轉義非'ASCII可列印'字元,或使用\x轉義非UTF-8可解析的位元組。 嘗試對RDB資料進行解碼可能會導致二進位制資料錯誤,可以通過使用--escape raw選項來避免這種情況。 另一種選擇是使用-e base64進行二進位制資料的Base64編碼。

解析dump檔案並在標準輸出上列印JSON:

[root@hankyoon ]# rdb -c json dump-5001.rdb
[{
"name":"yoon",
"name1":"hank",
"name2":"hankyoon"}]

將dump檔案解析為原始位元組,並在標準輸出上列印JSON:

[root@hankyoon ]# rdb -c json dump-5001.rdb --escape raw

生成記憶體報告
使用-c memory 執行會生成CSV報告,其中包含該鍵使用的近似記憶體。 --bytes C 和 --largest N 可用於將輸出限制為大於C位元組的鍵或N個最大鍵.

[root@hankyoon ]# rdb -c memory 5001dump.rdb --bytes 128 -f memory.csv

[root@hankyoon ]# cat memory.csv
database,type,key,size_in_bytes,encoding,num_elements,len_largest_element
0,list,lizards,241,quicklist,5,19
0,list,user_list,190,quicklist,3,7
2,hash,baloon,138,ziplist,3,11
2,list,armadillo,231,quicklist,5,20
2,hash,aroma,129,ziplist,3,11

引數:

database:            資料庫編號
type:                資料型別
key:                 鍵
size_in_bytes:       使用的記憶體:包括鍵,值和任何其他開銷
encoding:            RDB編碼型別
num_elements:        key中的value的個數
len_largest_element: key中的value的長度
expiry:              過期值

注意:記憶體使用情況是近似的。通常,實際使用的記憶體將略高於報告的記憶體。可以按鍵或資料庫編號或資料型別過濾報告。記憶體報告應有助於檢測由應用程式邏輯引起的記憶體洩漏。 它還將幫助優化Redis的記憶體使用。

查詢單鍵使用的記憶體:

查詢特定鍵使用的記憶體(執行整個記憶體報告非常耗時),使用redis-memory-for-key:

[root@hankyoon ]# redis-memory-for-key name

[root@hankyoon ]# redis-memory-for-key -s localhost -p 5001 -a mypassword name
Key                          name
Bytes                        111
Type                         hash
Encoding                     ziplist
Number of Elements           2
Length of Largest Element    8

比較RDB檔案:

使用--command diff選項,並將輸出通過管道傳遞到標準sort:

[root@hankyoon ]# rdb --command diff dump1.rdb | sort > dump1.txt

[root@hankyoon ]# rdb --command diff dump2.rdb | sort > dump2.txt

[root@hankyoon ]# kdiff3 dump1.txt dump2.txt

要限制檔案的大小,可以使用--key選項過濾鍵。

使用Redis協議:
使用protocol命令將RDB檔案轉換為redis協議流:

[root@hankyoon ]# rdb -c protocol dump.rdb
*4
$4
HSET
$9
users:123
$9
firstname
$8
Sripathi

Python解析器封裝指令碼:

from rdbtools import RdbParser, RdbCallback
from rdbtools.encodehelpers import bytes_to_unicode

class MyCallback(RdbCallback):
    ''' Simple example to show how callback works.
        See RdbCallback for all available callback methods.
        See JsonCallback for a concrete example
    '''

    def __init__(self):
        super(MyCallback, self).__init__(string_escape=None)

    def encode_key(self, key):
        return bytes_to_unicode(key, self._escape, skip_printable=True)

    def encode_value(self, val):
        return bytes_to_unicode(val, self._escape)

    def set(self, key, value, expiry, info):
        print('%s = %s' % (self.encode_key(key), self.encode_value(value)))

    def hset(self, key, field, value):
        print('%s.%s = %s' % (self.encode_key(key), self.encode_key(field), self.encode_value(value)))

    def sadd(self, key, member):
        print('%s has {%s}' % (self.encode_key(key), self.encode_value(member)))

    def rpush(self, key, value):
        print('%s has [%s]' % (self.encode_key(key), self.encode_value(value)))

    def zadd(self, key, score, member):
        print('%s has {%s : %s}' % (str(key), str(member), str(score)))


callback = MyCallback()
parser = RdbParser(callback)
parser.parse('/home/yoon/dump-5001.rdb')

一、rdb:根據要求分析這個RDB檔案

1、按json格式匯出rdb:

[root@hankyoon ]#  rdb --command json dump.rdb

2、匯出rdb中的keys:

[root@hankyoon ]#  rdb -c justkeys dump.rdb|uniq

3、匯出rdb中的values:

[root@hankyoon ]#  rdb -c justkeyvals dump.rdb

4、匯出rdb中keys的記憶體分析:

[root@hankyoon ]#  rdb -c memory dump.rdb

5、按RESP協議匯出RDB內容:

[root@hankyoon ]#  rdb -c protocol dump.rdb
  
  管道匯入
[root@hankyoon ]#  rdb --command protocol dump.rdb | nc 192.168.1.122 7777

6、分析RDB結果匯出到檔案:

[root@hankyoon ]#  rdb -c memory dump.rdb -f yoon.csv

7、匯出指定資料庫的keys:

[root@hankyoon ]#  rdb -c justkeyvals dump.rdb -n 0

8、匯出匹配(正則)的keys:

[root@hankyoon ]#  rdb --command justkeyvals --key ".*set*" dump.rdb

9、不匯出匹配(正則)的keys:

[root@hankyoon ]#  rdb --command justkeyvals --not-key ".*set*" dump.rdb

10、匯出指定型別的keys:

[root@hankyoon ]#  rdb --command json --type hash dump.rdb

11、匯出大於指定位元組的keys:

[root@hankyoon ]#  rdb --command memory --bytes 128  dump.rdb

12、匯出記憶體位元組排名前3個keys:

[root@hankyoon ]#  rdb --command memory --largest 3 dump.rdb

13、匯出指定編碼轉義:

[root@hankyoon ]#  rdb --command justkeyvals --escape raw dump.rdb

14、匯出keys(過期keys除外):

[root@hankyoon ]#  rdb --command memory --no-expire dump.rdb

15、匯出keys(給過期keys新增時間):

[root@hankyoon ]#  rdb --command memory --amend-expire 100 dump.rdb 

注意:
以上操作引數可以相互疊加使用,按照實際要求進行組合。並且可以匯出成csv檔案,匯入到資料庫裡進行聚合統計和監控。

二、redis-memory-for-key:檢視指定key的記憶體情況
檢視指定key的記憶體分析情況:(檢視該伺服器上key為hankyoon的記憶體情況)

[root@hankyoon ]#  redis-memory-for-key --server=192.168.163.134 --port=8379 hankyoon
Key                  hankyoon
Bytes                56
Type                 string

三、redis-profiler:RDB分析生成html
RDB分析結果到html檔案:

[root@hankyoon ]#  redis-profiler dump.rdb -f yoon.html