Redis大key扫描Python脚本

脚本评论3阅读模式

实现扫描redis实例中长度大于10240的key打印出来

Redis大key扫描Python脚本

find_bigkey.py

  1. #!/usr/bin/python
  2. import sys
  3. import redis
  4. def check_big_key(r, k):
  5.   bigKey = False
  6.   length = 0
  7.   try:
  8.     type = r.type(k)
  9.     if type == "string":
  10.       length = r.strlen(k)
  11.     elif type == "hash":
  12.       length = r.hlen(k)
  13.     elif type == "list":
  14.       length = r.llen(k)
  15.     elif type == "set":
  16.       length = r.scard(k)
  17.     elif type == "zset":
  18.       length = r.zcard(k)
  19.   except:
  20.     return
  21.   if length > 10240:
  22.     bigKey = True
  23.   if bigKey :
  24.     print db,k,type,length
  25. def find_big_key_normal(db_host, db_port, db_num):
  26.   r = redis.StrictRedis(host=db_host, port=db_port, db=db_num)
  27.   for k in r.scan_iter(count=1000):
  28.     check_big_key(r, k)
  29. def find_big_key_sharding(db_host, db_port, db_num, nodecount):
  30.   r = redis.StrictRedis(host=db_host, port=db_port, db=db_num)
  31.   cursor = 0
  32.   for node in range(0, nodecount) :
  33.     while True:
  34.       iscan = r.execute_command("iscan",str(node), str(cursor), "count", "1000")
  35.       for k in iscan[1]:
  36.         check_big_key(r, k)
  37.       cursor = iscan[0]
  38.       print cursor, db, node, len(iscan[1])
  39.       if cursor == "0":
  40.         break;
  41. if __name__ == '__main__':
  42.   if len(sys.argv) != 3:
  43.      print 'Usage: python ', sys.argv[0], ' host port '
  44.      exit(1)
  45.   db_host = sys.argv[1]
  46.   db_port = sys.argv[2]
  47.   r = redis.StrictRedis(host=db_host, port=int(db_port))
  48.   #nodecount = r.info()['nodecount']
  49.   nodecount = 1
  50.   keyspace_info = r.info("keyspace")
  51.   for db in keyspace_info:
  52.     print 'check ', db, ' ', keyspace_info[db]
  53.     if nodecount > 1:
  54.       find_big_key_sharding(db_host, db_port, db.replace("db",""), nodecount)
  55.     else:
  56.       find_big_key_normal(db_host, db_port, db.replace("db", ""))

PS:脚本21行if length > 10240:改成您指定的长度

安装python依赖

  1. pip install redis

扫描出大key

  1. python find_bigkey.py 127.0.0.1 6379 | tee -a bigkey.log

将bigkey.log丢给开发优化去吧

Wed Feb 20 11:15:49 CST 2019

 
  • 本文由 yeho 发表于 2019-02-20
  • 转载请务必保留本文链接:https://linuxeye.com/464.html
脚本

腾讯云COS上传、批量删除工具(Python)

腾讯云对象存储COS是类似于阿里云OSS,相比OSS,COS提供每月免费额度:存储空间50G、外网访问流量10G(内网免费)、免费读请求100万次、写请求10万次。对网站备份来说不错,但是,腾讯云提供...
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证