Skip to content

Instantly share code, notes, and snippets.

@tankala
Last active April 14, 2023 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tankala/c71c74853d8c0503bb1c780637d18c42 to your computer and use it in GitHub Desktop.
Save tankala/c71c74853d8c0503bb1c780637d18c42 to your computer and use it in GitHub Desktop.
Redis key expire listener

Redis key expire listener

This code listens to redis key expire notifications

Installation

Set config in Redis config file as "notify-keyspace-events Ex"

pip3 install redis

You will find full details here

import redis
# Whenever key expire notification comes this function get's executed
def event_handler(msg):
print("Handler", msg)
try:
key = msg["data"].decode("utf-8")
# If shadowKey is there then it means we need to proceed or else just ignore it
if "shadowKey" in key:
# To get original key we are removing the shadowKey prefix
key = key.replace("shadowKey:", "")
value = cache.get(key)
# Once we got to know the value we remove it from Redis and do whatever required
cache.delete(key)
print("Got Value: ", value)
except Exception as exp:
pass
# Creating Redis and pubsub Connection
cache = redis.Redis()
pubsub = cache.pubsub()
# Set config in config file "notify-keyspace-events Ex"
# Subscribing to key expire events and whenver we get any notification sending it to event_handler function
pubsub.psubscribe(**{"__keyevent@0__:expired": event_handler})
pubsub.run_in_thread(sleep_time=0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment