利用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

 

该脚本扫描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)
posted @ 2021-01-08 08:37  歪歪//  阅读(235)  评论(0编辑  收藏  举报