What is Redis Keyspace Notification?
In simple terms, it is a Publish-Subscriber mechanism that allows you to track and listen for changes in Redis datasets.
Using this feature, you can subscribe to a channel where Redis will be notifying you of any event that affects the dataset in Redis.
Configuring Redis Keyspace Notification
To use keyspace notification in Redis, you need to enable this feature. There are two ways to enable this feature:
- At Runtime
- In the configuration file.
At Runtime
To enable the keyspace notification feature during runtime, open the Redis CLI and run the command:
OK
The above command will enable keyspace notifications for your Redis server.
Hold on! We will discuss what KEA means in a short while.
Using configuration file
Enabling keyspace notification during runtime is only persistent until the server is restarted.
To set notifications permanently, edit the configuration as:
Next, locate the entry:
Change the value from an empty string to KEA as shown:
Save and close the File. Then, restart the server to apply the changes.
RKN Configuration Parameters
Now let us talk about what “KEA” means.
By default, keyspace notifications are disabled. This is done by setting the value of the notify-keyspace-events directive to an empty string.
To enable it, replace the value with a set of characters where each character denotes an event to be logged.
The characters you can use are as shown:
Hence, KEA will enable all notifications for all types of events.
Testing Keyspace Notification
Let us test the keyspace notification in practice. The first step is to ensure keyspace is enabled, as discussed in the previous sections.
Next, subscribe to the keyspace notification channel.
Open the Redis CLI and run the command as shown below:
The command above should return output as shown:
Open a new terminal session and log in to the Redis CLI to test for events.
Run the command:
OK
Go back to the terminal where you have subscribed to the keyspace notifications.
You should see a sample output as shown:
2) "__key*__:*"
3) "__keyspace@0__:mykey"
4) "set"
1) "pmessage"
2) "__key*__:*"
3) "__keyevent@0__:set"
4) "mykey"
You will notice that the notifications follow the subscribe pattern.
Redis logs the event with the pmessage type when running the SET command. The second is the channel with the name of the event.
The second is the key-event notification which holds the name of the key.
Conclusion
That’s it for this one. This article discussed how to enable and use the keyspace notification feature in Redis. This allows you to get notified when events occur in your database.
Thanks for reading & Stay tuned for more.