查找redis永不过期的key--python版本

import redis

host = '127.0.0.1'
port = 6379
output_file = 'never_expire_keys.txt'

# 连接到 Redis
r = redis.Redis(host=host, port=port)

# 查询每个键的 TTL,将永不过期的键写入到文件中
with open(output_file, 'w') as f_output:
    keys = r.keys("*")
    for key in keys:
        ttl = r.ttl(key)
        if ttl == -1:
            f_output.write(key.decode('utf-8') + '\n')

print("永不过期的键已写入到 {} 文件中".format(output_file))

16个库

import redis

host = '127.0.0.1'
port = 6379
output_file = 'never_expire_keys_all_dbs.txt'
db_count = 16  # Redis 默认支持的数据库数量

# 函数用于写入永不过期的键到文件
def write_keys_to_file(db_index, keys):
    with open(output_file, 'a') as f_output:  # 使用 'a' 模式以追加内容
        for key in keys:
            ttl = r.ttl(key)
            if ttl == -1:
                f_output.write(f"DB{db_index}:{key.decode('utf-8')}\n")

# 连接到 Redis
r = redis.Redis(host=host, port=port, db=0)  # 从数据库 0 开始

print("正在扫描所有数据库的永不过期的键...")
for db_index in range(db_count):
    # 切换到每个数据库
    r.select(db_index)
    keys = r.keys("*")
    write_keys_to_file(db_index, keys)

print(f"所有数据库中永不过期的键已写入到 {output_file} 文件中")
posted @ 2024-03-16 15:26  朝阳1  阅读(64)  评论(0)    收藏  举报