Skip to content

Instantly share code, notes, and snippets.

@smitp
Forked from zioproto/redis-delete-old-keys.py
Last active March 6, 2020 05:23
Show Gist options
  • Save smitp/978beadf9753ed01a0a7f9df2b1a0dc9 to your computer and use it in GitHub Desktop.
Save smitp/978beadf9753ed01a0a7f9df2b1a0dc9 to your computer and use it in GitHub Desktop.
Delete/List Redis Stale Keys
#!/usr/bin/env python
from __future__ import print_function
import redis
import sys
if len(sys.argv) < 2:
print("python redis_cleanup.py delete|list".format())
sys.exit(-1)
action = sys.argv[1]
pattern = sys.argv[2]
r = redis.StrictRedis(host='localhost', port=6379, db=0)
counter = 0
for key in r.scan_iter(pattern):
# if counter > 100:
# break
idle = r.object("idletime", key)
# idle time is in seconds. This is 180 days
if idle > (180 * 24 * 3600):
counter += 1
if action == "delete":
print("%10s %-15s %s" % (action, idle, key,))
r.delete(key)
elif action == "list":
print("%10s %-15s %s" % (action, idle, key,))
else:
print("%10s %-15s %s" % ("-", idle, key,))
print(counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment