暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

优雅遍历和删除特定开头的key

原创 陌殇流苏 2025-04-25
101

##### 遍历脚本

```

import redis

# Redis连接配置
redis_host = 'localhost'
redis_port = 6379
redis_db = 168
redis_password = '123' # 如果有密码取消注释

# 导出文件
output_file = 'redis_export_keys.txt'

# 多个前缀
prefix_list = ['bb_pu:u*', 'bb_pu:p*', 'bb_qu:u*', 'bb_qu:q*']

# 建立 Redis 连接
r = redis.StrictRedis(
  host=redis_host,
  port=redis_port,
  db=redis_db,
  password=redis_password, # 如有密码
  decode_responses=True
)

# 开始导出
with open(output_file, 'w', encoding='utf-8') as f:
  total_written = 0
  for prefix in prefix_list:
    print(f"🔍 开始扫描前缀:{prefix}")
    cursor = 0
    while True:
      cursor, keys = r.scan(cursor=cursor, match=prefix, count=10)
      for key in keys:
         ttl = r.ttl(key)
         if ttl == -1: # 不过期
           f.write(key + '\n')
           total_written += 1
           if total_written % 10000 == 0:
             print(f"已写入 {total_written} 个 key...")
       if cursor == 0:
         break

    print(f"✅ 前缀 {prefix} 扫描完成")

print(f"\n🎉 导出完成,共写入 {total_written} 个不过期 key 到:{output_file}")

```


##### 删除key

```

# encoding: utf-8 

import redis,sys 

# 连接到 Redis 

r = redis.Redis(host='xxxxxxx', port=6379, password="xxxxx", db=0) 

# 传入外部变量: 文件名 

del_fname=sys.argv[1] 

# 读取文件 

with open(del_fname, 'r') as file: 

  for line in file: 

    # 去除换行符 

    line = line.strip() 

    r.unlink(line) 

# 关闭文件 

file.close()

```

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论