一次性为Redis的键设置到期时间

首先

这是一种批量添加到Redis中批量设置过期时间的方法,适用于键值过多的情况。

我在注意以下事项。

    • pipeline処理で複数件同時に処理する

 

    • Redisに負荷をかけすぎないために複数件処理後に数秒sleepさせる

 

    expireの時間を分散させキー削除による負荷がかからないようにする

获取带有“expire”设置的键的列表。

将从keys获取的数据保存到文件中

$ redis-cli -h {host} -n {database} keys "*" > keys

给Redis的键添加到期时间

从文件中grep特定的键,并加上过期标记。

$ grep {expire_key_name} keys | python set_expires.py
 # -*- coding: utf-8 -*-

import redis
import time
import sys
import random

EXPIRATION_SECONDS_MIN = 86400 * 10  # 10日
EXPIRATION_SECONDS_MAX = 86400 * 20  # 20日


def main():
    set_expire_keys()


def set_expire_keys():
    redis_cli = _create_client()
    pipe = redis_cli.pipeline()
    line_num = 0
    for line in sys.stdin:
        key_name = line.strip()
        # 一度に大量のキーが消えるのを防ぐために乱数で期間をバラす
        expiration_time = random.randint(EXPIRATION_SECONDS_MIN, EXPIRATION_SECONDS_MAX)
        pipe.expire(key_name, expiration_time)
        # 1万キーごとにexecute
        if line_num % 10000 == 0:
            print("{} lines proceeded.".format(line_num))
            pipe.execute()
            # Redisへの負荷を考慮して3秒停止
            time.sleep(3)
            pipe = redis_cli.pipeline()
        line_num += 1
    pipe.execute()
    print("{} lines proceeded.".format(line_num))
    print("complete!!")


def _create_client():
    redis_cli = redis.Redis(
        host="localhost",
        port=6379,
        db=1
        )
    return redis_cli


if __name__ == "__main__":
    main()
广告
将在 10 秒后关闭
bannerAds