Python小程序扫描清理Redis中的key
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python小程序扫描清理Redis中的key,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2581字,纯文字阅读大概需要4分钟。
内容图文
![Python小程序扫描清理Redis中的key](/upload/InfoBanner/zyjiaocheng/867/3a556a1351c44ef98736aeafbf748dda.jpg)
场景
项目中很多地方使用Redis,有的用于缓存,有的直接做为存储,有的key设置有过期,有的key没有过期时间。
随着时间增长,Redis存储数据越来越多,消耗内存不断增长;
无论测试或生产环境,总内存是有限的;
有的key可能临时或测试使用的;
于是有了清理Redis key的需求。
Redis命令
查看key个数:
dbsize
info keyspace
查看内存情况:
info memory
通配符扫描key:
SCAN cursor [MATCH pattern] [COUNT count]
Python小程序
Linux服务器一般都自带Python,这里用Python编写2个小程序,分别用于扫描key和扫描并删除key。
扫描key:
#!/usr/bin/env python
# Scan keys in Redis.
# Author: cdfive
from redis import Redis
import time
def RedisScan(host, port, password, db, cursor, pattern, count):
start_time = time.time()
client = Redis(host=host, port=port, password=password, db=db)
counts, other_cursor_counts = 0, 0
while True:
cursor, keys = client.scan(cursor, pattern, count)
length = len(keys)
if length > 0:
for key in keys:
counts += 1
print("[%s][%s]%s,cursor=%s" % (
int(time.time() - start_time), counts, key.decode("utf-8"), cursor))
else:
other_cursor_counts += 1
print("[%s][other_curosr]other_cursor_counts=%s,cursor=%s" % (
int(time.time() - start_time), other_cursor_counts, cursor))
if cursor == 0:
break
client.close()
print("[%s]counts=%s,cursor=%s,other_cursor_counts=%s"
% (int(time.time() - start_time), counts, cursor, other_cursor_counts))
RedisScan("localhost", 6379, "123456", 0, 0, "*xxx*", 1000)
扫描并删除key:
#!/usr/bin/env python
# Scan and delete keys in Redis.
# Author: cdfive
from redis import Redis
import time
def RedisScanDelete(host, port, password, db, cursor, pattern, count, batch_delete_size):
start_time = time.time()
client = Redis(host=host, port=port, password=password, db=db)
counts, other_cursor_counts = 0, 0
delete_keys = []
while True:
cursor, keys = client.scan(cursor, pattern, count)
length = len(keys)
if length > 0:
index = 0
for key in keys:
index += 1
counts += 1
print("[%s][%s]%s,cursor=%s" % (
int(time.time() - start_time), counts, key.decode("utf-8"), cursor))
delete_keys.append(key)
if (len(delete_keys) >= batch_delete_size or index >= length) and len(delete_keys) > 0:
client.delete(*delete_keys)
delete_keys = []
else:
other_cursor_counts += 1
print("[%s][other_curosr]other_cursor_counts=%s,cursor=%s" % (
int(time.time() - start_time), other_cursor_counts, cursor))
if cursor == 0:
break
client.close()
print("[%s]counts=%s,cursor=%s,other_cursor_counts=%s"
% (int(time.time() - start_time), counts, cursor, other_cursor_counts))
RedisScanDelete("localhost", 6379, "123456", 0, 0, "*xxx*", 1000, 100)
注:RedisScanDelete
最后1个参数为batch_delete_size
,用于通过pipeline批量删除key,提高删除效率。
内容总结
以上是互联网集市为您收集整理的Python小程序扫描清理Redis中的key全部内容,希望文章能够帮你解决Python小程序扫描清理Redis中的key所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。