版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/keplerpig/article/details/81393946
#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#scan 0号数据库的键空间,获取空闲时长大于指定时间的键的列表,达到获取业务死键的作用
#日期: 2018-08-03
import redis
import time
TIME_THRESHOLD_SECOND = 1296000 # 获取idletime时长超过TIME_THRESHOLD_SEC秒数键打印. 默认:15天
COUNT = 200 #scan每次返回的键个数,建议不要太大,避免O(n)的n过大出现慢查询. 默认:200个
YEILD_SECOND = 0.05 #每次scan后,sleep YEILD_SECOND秒;休眠的目的是避免干扰线上服务器
def get_key_idletime():
host="127.0.0.1";
redisPort=6379
pwd=""
dbNum=0
tempHost=input("input redis host:")
if len(tempHost)>0:
host=tempHost
else:
print("default host:",host)
pwd=input("input redis password:")
if len(pwd)==0:
print("warning password is empty")
try:
redisPort=int(input("input redis port:"))
except Exception:
print("default redis port: ",redisPort)
try:
dbNum=int(input("input redis db:"))
except Exception:
print("default redis db: ",dbNum)
r = redis.StrictRedis(host=host,port=redisPort,password=pwd,db=dbNum)
cursor = '0'
while cursor != 0:
cursor, data = r.scan(cursor=cursor, count=COUNT)
for key in data:
key_idletime = r.object("idletime",key)
if key_idletime > TIME_THRESHOLD_SECOND:
print (key,key_idletime)#这里建议改为写入到文件中或者直接增加处理逻辑
time.sleep(YEILD_SECOND)
get_key_idletime()
警告!警告!警告!重要的事说三遍!重要的事说三遍!重要的事说三遍!
该程序虽然能检查很久没有访问的KEY,但是具体要不要清除必须根据自身业务来处理,如果KEY的命名有规则还好,如果无规则,清理时一定要慎重!慎重!慎重!
我机器用的版本是python3.7,执行前需要自行安装python redis 客户端哟!!!