From Redis Keyspace Notifications
Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Examples of events that can be received are:
All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.
Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.
So, if you need just pub/sub, there is no need of extra configuration regarding Keyspace Notifications
Answer from usuario on Stack OverflowFrom Redis Keyspace Notifications
Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Examples of events that can be received are:
All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.
Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.
So, if you need just pub/sub, there is no need of extra configuration regarding Keyspace Notifications
key-space-notifications and pub/sub are 2 different concepts.
PUB/SUB: It's usual method publishing data to a channel and other clients can subscribe to the same channel by it's name. published messages are characterised into channels, without knowledge of what (if any) subscribers there may be.
This is enabled by default. messages are not persisted here, and once delivered/lost, messages cannot be retrieved.
key-space-notifications: This also a way of subscribing to Pub/Sub channels in order to receive events by the clients.
This we need to enable manually as this consumes little more CPU. Use below code to enable this
redisClient.configSet("notify-keyspace-events", "Ex");
we can subscribe to 2 different channels
- Key-space channel: receives the name of the event as message.
- Key-event channel: receives the name of the key as message.
example: To subscribe to key expired events, use the below code
export const subscribeForExpiry = () => {
//.: Subscribe to the "notify-keyspace-events"
// channel used for expired type events
client.configSet("notify-keyspace-events", "Ex");
const sub = client.duplicate();
sub.connect();
sub.subscribe(
`__keyevent@${process.env.REDIS_DATABASE_INDEX}__:expired`,
(key) => {
console.log("key=> ", key);
// do something with key, can't retrieve value here
}
);
};