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
原文地址:https://www.cnblogs.com/hankyoon/p/13603192.html