1
+ // A sample subscriber showing how the subscribe method and pSubscribe method work.
2
+ // https://redis.io/commands/subscribe/
3
+ // https://redis.io/commands/pSubscribe/
4
+ // This consumes messages published by pubsub-publisher.js
5
+
6
+ import { createClient } from 'redis' ;
7
+
8
+ // Create and connect client before executing any Redis commands.
9
+ const client = createClient ( ) ;
10
+ await client . connect ( ) ;
11
+
12
+ // Each subscriber needs to connect individually therefore we duplicate the client.
13
+ const channel1Sub = client . duplicate ( ) ;
14
+ const channel2Sub = client . duplicate ( ) ;
15
+ const noChannelsSub = client . duplicate ( ) ;
16
+ const allChannelsSub = client . duplicate ( ) ;
17
+
18
+ await channel1Sub . connect ( ) ;
19
+ await channel2Sub . connect ( ) ;
20
+ await noChannelsSub . connect ( ) ;
21
+ await allChannelsSub . connect ( ) ;
22
+
23
+ // This subscriber only will receive messages from channel 1 as they are using the subscribe method and subscribed to chan1nel.
24
+ await channel1Sub . subscribe ( 'chan1nel' , ( message ) => {
25
+ console . log ( `Channel1 subscriber collected message: ${ message } ` ) ;
26
+ } , true ) ;
27
+
28
+ // This subscriber only will receive messages from channel 2 as they are using the subscribe method and subscribed to chan2nel.
29
+ await channel2Sub . subscribe ( 'chan2nel' , ( message ) => {
30
+ console . log ( `Channel2 subscriber collected message: ${ message } ` ) ;
31
+ } , true ) ;
32
+
33
+ // This subscriber will not receive any messages as its channel does not exist.
34
+ await noChannelsSub . subscribe ( 'chan*nel' , ( message ) => {
35
+ console . log ( `This message will never be seen as we are not using pSubscribe here. ${ message } ` ) ;
36
+ } , true ) ;
37
+
38
+ // This subscriber receive messages from both channel 1 and channel 2 using the pSubscribe method.
39
+ await allChannelsSub . pSubscribe ( 'chan*nel' , ( message , channel ) => {
40
+ console . log ( `Channel ${ channel } sent message: ${ message } ` ) ;
41
+ } , true ) ;
0 commit comments