This code listens to redis key expire notifications
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) |