Redis Expired Keys Notification
1 min readMar 16, 2020
We can get notification when the key expires in redis. This feature can be implemented by Redis Keyspace notification. For this we have to set configuration (notify-keyspace-events “KEx”) in the redis.conf file.
K for keyspace events, E for keyevent events and x for expire. This configuration informs us when any key is expired.
Set configuration from redis-cli — config set notify-keyspace-events KEx
OR
Set configuration from redis.conf file — notify-keyspace-events “KEx”
Python Code to get notification of expired keys-
#importing redis
import redis#connecting redis
redis_connection = redis.StrictRedis(host='localhost', port=6379, db=0)#publish of redis events
redis_subscriber = redis_connection.pubsub()"""
subscribe event for all keys. * means all the keys, if we want any specific key we have to give #that key name.
"""
redis_subscriber.psubscribe('__keyspace@0__:*')#listening message or notification of redis event.
for msg in redis_subscriber.listen():
print(msg)