0

I am working on a node JS app that connect to redis server and subscribe to a channel to get the messages. There is a bit of confusion, should we really enable "key space notifications" on redis config to get the events in client

The same scenario I have tried using rdis cli, with which i see "key space notifications" are not enabled at the same time I have subscribed to a channel with a pattern, so when ever I publish a message from the other client, I am able to capture that event in subscribed client.

Is the "key space notifications" mandatory , but the POC says other way.

Does any one know what should be the right approach here, subscribing to channel is suffice to get messages, and its nothing to do with "key-space-notifications" ??

enter image description here

Amaravathi
  • 115
  • 1
  • 2
  • 6

2 Answers2

0

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

usuario
  • 2,132
  • 1
  • 10
  • 26
0

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

  1. Key-space channel: receives the name of the event as message.
  2. 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
    }
  );
};
ajaykumar mp
  • 487
  • 5
  • 12