栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Redis大key扫描Python脚本

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redis大key扫描Python脚本

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

find_bigkey.py
    #!/usr/bin/python
    import sys
    import redis
    def check_big_key(r, k):
      bigKey = False
      length = 0
      try:
        type = r.type(k)
        if type == "string":
          length = r.strlen(k)
        elif type == "hash":
          length = r.hlen(k)
        elif type == "list":
          length = r.llen(k)
        elif type == "set":
          length = r.scard(k)
        elif type == "zset":
          length = r.zcard(k)
      except:
        return
      if length > 10240:
        bigKey = True
      if bigKey :
        print db,k,type,length
    def find_big_key_normal(db_host, db_port, db_num):
      r = redis.StrictRedis(host=db_host, port=db_port, db=db_num)
      for k in r.scan_iter(count=1000):
        check_big_key(r, k)
    def find_big_key_sharding(db_host, db_port, db_num, nodecount):
      r = redis.StrictRedis(host=db_host, port=db_port, db=db_num)
      cursor = 0
      for node in range(0, nodecount) :
        while True:
          iscan = r.execute_command("iscan",str(node), str(cursor), "count", "1000")
          for k in iscan[1]:
            check_big_key(r, k)
          cursor = iscan[0]
          print cursor, db, node, len(iscan[1])
          if cursor == "0":
            break;
    if __name__ == '__main__':
      if len(sys.argv) != 3:
         print 'Usage: python ', sys.argv[0], ' host port '
         exit(1)
      db_host = sys.argv[1]
      db_port = sys.argv[2]
      r = redis.StrictRedis(host=db_host, port=int(db_port))
      #nodecount = r.info()['nodecount']
      nodecount = 1
      keyspace_info = r.info("keyspace")
      for db in keyspace_info:
        print 'check ', db, ' ', keyspace_info[db]
        if nodecount > 1:
          find_big_key_sharding(db_host, db_port, db.replace("db",""), nodecount)
        else:
          find_big_key_normal(db_host, db_port, db.replace("db", ""))

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

安装python依赖
    pip install redis
扫描出大key
    python find_bigkey.py 127.0.0.1 6379 | tee -a bigkey.log

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

Wed Feb 20 11:15:49 CST 2019

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/10312.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号