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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM