做项目过程如果遇到缓存不一致的问题,通过RDM工具查询也能解决,但效率稍微慢了点,通常不允许缓存中存在过多未设置缓存时间的key,如果需要整理出哪些key需要手动清理,可以通过脚本来整理出来
Bash脚本方式
现将正则的key输入到文本文件,再进行迭代查看 ttl 输出控制台
#!/bin/sh host=localhost port=6379 db=0 pwd=comall redis-cli -h $host -p $port -n $db -a $pwd keys "*_beijing" > keys.txt more keys.txt | grep -v ^$ | while read mykey do result=`redis-cli -h $host -p $port -n $db -a $pwd -c ttl $mykey` if [ $result -eq -1 ] then echo $mykey fi done
Python3 查看Redis中所有未设置过期时间或时间过长的Key
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import redis import time if __name__ == '__main__': # r = redis.Redis(host='127.0.0.1',port=6379,db=0) _h = 'localhost' _port = 6379 _db = 0 _auth = 'comall' max_ttl = 604800 # 7天 pool = redis.ConnectionPool(host=_h, port=_port, db=-_db, password=_auth) r = redis.StrictRedis(connection_pool=pool, decode_responses=True) # r = redis.Redis(host=_h, port=_port, db=_db, password=_auth) print(type(r)) del_info = {} keys = r.keys() # 所有keys # keys = r.keys("*_beijing") # 有规则的keys bit_time = set() for key in keys: time.sleep(0.1) key = key.decode() ttl = r.pttl(key) if ttl == -1 or ttl > max_ttl: spl = key.replace('_beijing', '').split('#') k = spl[0] print(key, 'ttl={}'.format(ttl)) if ttl > max_ttl and k not in bit_time: bit_time.add(k) if del_info.get(k): del_info[k] = del_info.get(k) + 1 else: del_info[k] = 1 # r.delete(key) # print(" 删除的key是 {0}".format(key)) print('大于7天的keys', bit_time) print('无过期的keys', del_info) # 迭代删除 # suffix = '#*_beijing' # r.delete(*r.keys('order_sales' + suffix)) # print(r.keys('order_sales' + suffix))
示例日志
... region_children#340103_beijing ttl=-1 大于7天的keys {'goods_combine_item', 'marketing_category', 'subsiteRegionKey', 'order_sales', 'promotion_type_ids'} 无过期的keys {'region_children': 3365, 'section': 11, 'region': 17, 'subsiteRegionKey': 1, 'marketing_category': 1, 'order_sales': 4, 'product': 2, 'goods_combine_item': 2, 'promotion_type_ids': 2, 'brand': 2, 'categoryAll': 1}
未经允许请勿转载:程序喵 » Python3 查看Redis中所有未设置过期时间或时间过长的Key