1、背景

在redis中,对于一个很大的key,例如hash类型,直接查看其值会非常慢,于是想到写个脚本通过增量迭代来获取

2、具体的脚本如下:

功能:扫描redis某个key里面的所有元素
使用方法:python bigkey_save_values.py "zyyset" "*" 100

3、python脚本实现如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-  
#功能:扫描某个key里面的所有元素
#使用方法:python bigkey_save_values.py "zyyset" "m*" 100
#如需获取全部的元素:python bigkey_save_values.py "zyyset" "*" 100
__author__ = "lcl"  
import sys
import redis 
import os 
  
pool=redis.ConnectionPool(host='192.168.225.128',port=6379,db=0)  
r = redis.StrictRedis(connection_pool=pool)  
#指定key
key = sys.argv[1]
#扫描匹配值
match = sys.argv[2]
#每次匹配数量
count = sys.argv[3]
#总数量
total = 0
#获取当前路径
path = os.getcwd()
keytype = r.type(key)
print "key的类型为%s" % (keytype)
#扫描到的key输出的文件
txt = path+"/%s.txt" % (key)

#打开文件
#f = open(txt,"w")
def list_iter(name):
    list_count = r.llen(key)
    for index in range(list_count):
        yield r.lindex(key, index)

if keytype=='list':
    f = open(txt,"w")
    for item in list_iter(key):
#将匹配到对应key中的member/score输出到文件中
        f.write("%s %s" % (item,"\n"))
        total = total+1
    f.close

elif keytype=='hash':
    f = open(txt,"w")
    for item in r.hscan_iter(key,match = match,count = count):
#将匹配到对应key中的member/score输出到文件中
        f.write("%s %s" % (item,"\n"))
        total = total+1
    f.close
 
elif keytype=='set':
    f = open(txt,"w")
    for item in r.sscan_iter(key,match = match,count = count):
        f.write("%s %s" % (item,"\n"))
        total = total+1
    f.close

elif keytype=='zset':
    f = open(txt,"w")
    for item in r.zscan_iter(key,match = match,count = count):
        f.write("%s %s" % (item,"\n"))
        total = total+1
    f.close

else:
    print("key的类型为string,value为:" + r.get(key))

print "key:%s的match:%s的数量为:%d" % (key,match,total)

linda玲
438 声望27 粉丝

每天进步一点点