LoginSignup
15
15

More than 5 years have passed since last update.

Redisのキーに一括でExpireを設定する

Last updated at Posted at 2015-01-12

はじめに

Redisのキーが増えすぎた場合などに対して一括でExpireを付ける方法です.

以下のことに気を付けています.

  • pipeline処理で複数件同時に処理する
  • Redisに負荷をかけすぎないために複数件処理後に数秒sleepさせる
  • expireの時間を分散させキー削除による負荷がかからないようにする

expireをつけたいキー一覧を取得

keysで得たデータをファイルに保存する

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

Redisのキーにexpireを付与

ファイルから特定のキーをgrepしてexpireをつける

$ grep {expire_key_name} keys | python set_expires.py
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()
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15