diff --git a/docs/pub-sub.md b/docs/pub-sub.md index 4b0e138d8ac..75ff5610140 100644 --- a/docs/pub-sub.md +++ b/docs/pub-sub.md @@ -4,12 +4,17 @@ 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`: +Subscribing requires a dedicated stand-alone client. +Once `.subscribe()` is called on a client it can only be used to subscribe to additional channels or unsubscribe from some. +But you can subscribe to many Redis channel with the same `RedisClient`. +Publishing can be done on any non-subscriber client. + +You can create a new client by `.duplicate()`ing an existing `RedisClient`: ```typescript -const subscriber = client.duplicate(); -subscriber.on('error', err => console.error(err)); -await subscriber.connect(); +const subClient = client.duplicate(); +subClient.on('error', err => console.error(err)); +await subClient.connect(); ``` When working with a `RedisCluster`, this is handled automatically for you. @@ -33,10 +38,11 @@ The event listener signature is as follows: ```javascript const listener = (message, channel) => console.log(message, channel); -await client.subscribe('channel', listener); -await client.pSubscribe('channe*', listener); +await subClient.subscribe('channel', listener); +await subClient.subscribe(['channel-a', 'channel-b'], listener); +await subClient.pSubscribe('channe*', listener); // Use sSubscribe for sharded Pub/Sub: -await client.sSubscribe('channel', listener); +await subClient.sSubscribe('channel', listener); ``` ## Publishing @@ -52,23 +58,23 @@ await client.sPublish('channel', 'message'); The code below unsubscribes all listeners from all channels. ```javascript -await client.unsubscribe(); -await client.pUnsubscribe(); +await subClient.unsubscribe(); +await subClient.pUnsubscribe(); // Use sUnsubscribe for sharded Pub/Sub: -await client.sUnsubscribe(); +await subClient.sUnsubscribe(); ``` To unsubscribe from specific channels: ```javascript -await client.unsubscribe('channel'); -await client.unsubscribe(['1', '2']); +await subClient.unsubscribe('channel'); +await subClient.unsubscribe(['1', '2']); ``` To unsubscribe a specific listener: ```javascript -await client.unsubscribe('channel', listener); +await subClient.unsubscribe('channel', listener); ``` ## Buffers @@ -76,11 +82,11 @@ await client.unsubscribe('channel', listener); Publishing and subscribing using `Buffer`s is also supported: ```javascript -await subscriber.subscribe('channel', message => { +await subClient.subscribe('channel', message => { console.log(message); // }, true); // true = subscribe in `Buffer` mode. -await subscriber.publish(Buffer.from('channel'), Buffer.from('message')); +await subClient.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.