Redis provides a useful feature called keyspace notifications, which allows applications to receive events whenever certain operations happen inside Redis.
By default, Redis keyspace notifications are disabled. If your application needs to listen for events such as expired keys, you first need to enable the appropriate notify-keyspace-events configuration.
In a K8s Redis setup, the Redis configuration is stored inside a Kubernetes ConfigMap called redis-config. When keyspace notifications are disabled, the configuration will look like this:
Notice the following uncommented line. This disables it:
This guide will walk you through how to enable Redis key expiration notifications in Kubernetes, including updating the Redis ConfigMap, restarting the Redis StatefulSet, and verifying the configuration using redis-cli.
Understanding notify-keyspace-events Ex
For monitoring key expiration events, the important Redis configuration used here is:
The characters in Ex have specific meanings:
E = Keyevent events
x = Expired events
Together, Ex tells Redis to publish keyevent notifications for expired keys.
Edit the Redis ConfigMap
You can edit the Redis ConfigMap using the following command:
Inside the ConfigMap, find the commented configuration line:
Uncomment the line so that it becomes:
Save and exit the ConfigMap editor.
Restart the Redis StatefulSet
Updating the ConfigMap does not necessarily mean that the Redis processes already running inside your pods will immediately start using the new configuration.
The Redis pods therefore need to be restarted so that Redis starts with the updated configuration.
Restart the Redis StatefulSet using:
Wait until all Redis pods have restarted and returned to the Running state.
You can check the status of the pods using:
Verify the Redis Configuration
Once all Redis pods are running again, exec into one of the Redis pods. For example:
Start the Redis CLI:
If Redis requires authentication, authenticate using the Redis password:
If authentication is successful, Redis should return:
Now check whether Redis loaded the new keyspace notification configuration:
You should receive output similar to:
Redis may display the characters as xE even though the configuration was entered as Ex. The order does not change the intended configuration: keyevent notifications for expired keys are enabled.
Conclusion
At this point, Redis keyevent notifications for expired keys are enabled. Applications can now subscribe to the appropriate Redis keyevent channel and react when keys expire instead of continuously polling Redis for changes.
#redis #K8s
0 Comments