首页 > 编程语言 > 详细

利用python脚本统计和删除redis key

时间:2021-01-08 09:23:09      阅读:26      评论:0      收藏:0      [点我收藏+]

该脚本扫描redis中所有的key,用于分析redis内存数据的key构成,扫描并保存文件,需要python支持redis模块。

#!/usr/bin/env python # -*- coding: utf-8 -*- #jack chen import os, sys, time import redis def redis_scan(): try: redisconn = redis.StrictRedis(host="xx.xx.xx.xx", port=6379, db=0) #不同db需要修改 except Exception as e: print("connect redis error") sys.exit(1) cursor = 1 isNoe = True file = open(‘rediskey‘, ‘a+‘) while cursor != 0: if isNoe: cursor = 0 isNoe = False key = redisconn.scan(cursor, count=2000) #每次拿2000个key time.sleep(0.05) if len(key[1]) == 0: print("key scan finish") else: for n in key[1]: n = bytes.decode(n) file.write(n) file.write("\n") cursor = key[0] file.close() redis_scan()

删除key

提前把key保存到key.txt文件中,然后读取一行一行执行删除key的动作。

#!/bin/env python # -*- coding: UTF-8 -*- #function: 根据文件列表删除key,一行一个redis key #authors: jack chen import os, sys import redis import time conn = redis.StrictRedis(host="xx.xx.xx.xx",port=6379,db=0) #注意redis的db with open(‘key.txt‘) as file: for line in file: time.sleep(0.001) keyname = line.rstrip(‘\n‘) conn.delete(keyname) print("key: %s delete ok" %keyname)

利用python脚本统计和删除redis key

 

该脚本扫描redis中所有的key,用于分析redis内存数据的key构成,扫描并保存文件,需要python支持redis模块。

#!/usr/bin/env python # -*- coding: utf-8 -*- #jack chen import os, sys, time import redis def redis_scan(): try: redisconn = redis.StrictRedis(host="xx.xx.xx.xx", port=6379, db=0) #不同db需要修改 except Exception as e: print("connect redis error") sys.exit(1) cursor = 1 isNoe = True file = open(‘rediskey‘, ‘a+‘) while cursor != 0: if isNoe: cursor = 0 isNoe = False key = redisconn.scan(cursor, count=2000) #每次拿2000个key time.sleep(0.05) if len(key[1]) == 0: print("key scan finish") else: for n in key[1]: n = bytes.decode(n) file.write(n) file.write("\n") cursor = key[0] file.close() redis_scan()

删除key

提前把key保存到key.txt文件中,然后读取一行一行执行删除key的动作。

#!/bin/env python # -*- coding: UTF-8 -*- #function: 根据文件列表删除key,一行一个redis key #authors: jack chen import os, sys import redis import time conn = redis.StrictRedis(host="xx.xx.xx.xx",port=6379,db=0) #注意redis的db with open(‘key.txt‘) as file: for line in file: time.sleep(0.001) keyname = line.rstrip(‘\n‘) conn.delete(keyname) print("key: %s delete ok" %keyname)

利用python脚本统计和删除redis key

原文:https://www.cnblogs.com/shiyueyangne/p/14249785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!