python 批量删除 redis 大量数据

复制代码
#!/usr/bin/env python
# Scan and delete keys in Redis.
# Author: cdfive
from redis import Redis
import time


def RedisScanAndDelete(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))


RedisScanAndDelete("localhost", 6379, "123456", 0, 0, "*xxx*", 1000, 100)
复制代码

参考教程:https://blog.51cto.com/u_56701/6473475

posted @   淋哥  阅读(383)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2018-06-27 验证码识别 图像降噪 Python (一)
2016-06-27 如何创建PostgreSQL数据库
2016-06-27 在linux系统下检查postgresql数据库安装,登录数据库及简单的查看数据库
2016-06-27 PostgreSQL连接python,postgresql在python 连接,创建表,创建表内容,插入操作,选择操作,更新操作,删除操作。
点击右上角即可分享
微信分享提示