For some reason, I was figuring out a way to be able to listen to Redis so I can fire callbacks when the Redis command or event is encountered.
I wanted to do something like:
When a key gets removed from the sorted set, it will trigger a script that will notify a user.
Browsing online, I came across the so-called Redis Keyspace Notifications. It basically acts as a Pub/Sub mechanism that enables clients to subscribe to a Redis channel and receive “published” events whenever a Redis command or data alteration is encountered. The feature is available since version 2.8, apparently.
The said notifications are enabled using the
notify-keyspace-events of redis.conf or via the CONFIG SET. It is disabled by default.
Setup will look something like:
zE looks so random if you weren’t briefed that each character in that string has a meaning.
Below is the list of variable mapping for keyspace events:
For my particular case, I needed to use “
zE” string because I want to catch the name of the key (and not the name of the event) when
zrem, which is a sorted set command, is encountered.
Keyspace v.s. Keyevent
Let’s cut to the chase! Use keyspace if you want to receive the name of the event. Use keyevent if you want to receive the name of the key.
TILception (TIL within a TIL): If you want to enable all events, use “KEA”.
So, here’s an example of what I played around with:
As I told earlier, I wanted to catch the “key” as a message and not the “event”. So, the message variable in the above code will output the key.
Now, in your redis-cli, if you try to prepare a sorted set by using
zadd and then doing a
zrem, you will see the output in your console.
Now it’s time for me to send that notification!