Skip to content

Instantly share code, notes, and snippets.

@zioproto
Last active March 3, 2023 18:45
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zioproto/ac434a5067605a4f093d5925c8695ec3 to your computer and use it in GitHub Desktop.
Save zioproto/ac434a5067605a4f093d5925c8695ec3 to your computer and use it in GitHub Desktop.
Delete Redis Stale Keys
#!/usr/bin/env python
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
# To debug code on a single key you can use this instead of the for loops:
# key = r.randomkey()
# Delete all keys not accessed since 'idletime'
for key in r.scan_iter("*"):
idle = r.object("idletime", key)
# idle time is in seconds
if idle > 3600:
r.delete(key)
# Delete all keys without a TTL to expire
for key in r.scan_iter("*"):
# ttl is a type long or -1 if it is not set
if r.ttl(key) == -1:
r.delete(key)
@f9n
Copy link

f9n commented Jan 14, 2020

Delete all keys without a TTL with Redis Sentinel

from redis.sentinel import Sentinel

sentinel_service_name = 'githubredis'
redis_password = 'secret_password'
sentinels = [
    ('10.250.200.10', 26379),
    ('10.250.200.11', 26379),
    ('10.250.200.12', 26379),
]
socket_timeout = 0.5

def main():
    sentinel = Sentinel(sentinels=sentinels, password=redis_password, socket_timeout=socket_timeout)
    master = sentinel.master_for(service_name=sentinel_service_name, socket_timeout=socket_timeout)

    # Delete all keys without a TTL to expire
    for key in master.scan_iter("*"):
        # ttl is a type long or -1 if it is not set
        if master.ttl(key) == -1:
            print(key)
            master.delete(key)


if __name__ == "__main__":
    main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment