Skip to content

Latest commit

 

History

History
88 lines (63 loc) · 2.36 KB

pub-sub.md

File metadata and controls

88 lines (63 loc) · 2.36 KB

Pub/Sub

The Pub/Sub API is implemented by RedisClient and RedisCluster.

Pub/Sub with RedisClient

Pub/Sub requires a dedicated stand-alone client. You can easily get one by .duplicate()ing an existing RedisClient:

const subscriber = client.duplicate();
subscriber.on('error', err => console.error(err));
await subscriber.connect();

When working with a RedisCluster, this is handled automatically for you.

sharded-channel-moved event

RedisClient emits the sharded-channel-moved event when the "cluster slot" of a subscribed Sharded Pub/Sub channel has been moved to another shard.

The event listener signature is as follows:

(
  channel: string,
  listeners: {
    buffers: Set<Listener>;
    strings: Set<Listener>;
  }
)

Subscribing

const listener = (message, channel) => console.log(message, channel);
await client.subscribe('channel', listener);
await client.pSubscribe('channe*', listener);
// Use sSubscribe for sharded Pub/Sub:
await client.sSubscribe('channel', listener);

⚠️ Subscribing to the same channel more than once will create multiple listeners which will each be called when a message is recieved.

Publishing

await client.publish('channel', 'message');
// Use sPublish for sharded Pub/Sub:
await client.sPublish('channel', 'message');

Unsubscribing

The code below unsubscribes all listeners from all channels.

await client.unsubscribe();
await client.pUnsubscribe();
// Use sUnsubscribe for sharded Pub/Sub:
await client.sUnsubscribe();

To unsubscribe from specific channels:

await client.unsubscribe('channel');
await client.unsubscribe(['1', '2']);

To unsubscribe a specific listener:

await client.unsubscribe('channel', listener);

Buffers

Publishing and subscribing using Buffers is also supported:

await subscriber.subscribe('channel', message => {
  console.log(message); // <Buffer 6d 65 73 73 61 67 65>
}, true); // true = subscribe in `Buffer` mode.

await subscriber.publish(Buffer.from('channel'), Buffer.from('message'));

NOTE: Buffers and strings are supported both for the channel name and the message. You can mix and match these as desired.