The prototype of the Publish/subscribe pattern is this: There are two classes of principals, producers and consumers, and the producer puts the tasks that need to be processed into the task queue, while the consumer continuously reads the tasks from the task queue and executes them. Producers and consumers only need to define the format of the task queue in advance, and neither side needs to know the details of the other's implementation. Since both parties interact based on the task queue, it is easier to add new producers or new consumers. In general, the Publish/subscribe model has a loosely coupled, easy-to-extend feature. Publish/Subscribe with publish and subscribe commands
Redis provides very good support for the Publish/subscribe model, providing publish and subscribe two commands that make it easy to publish and subscribe between multiple clients. First open a REDIS-CLI client, this client as a consumer, to subscribe to a channel message
Redis 127.0.0.1:6379> SUBSCRIBE channel1
Reading messages ... (Press Ctrl-c to quit)
1) "Subscribe"
2) "Channel1"
3) (integer) 1
We subscribed to the Channel1 channel, then the consumer program blocked and entered the listening mode.
Then we are opening a REDIS-CLI client, as a producer, to publish the message
Redis 127.0.0.1:6379> PUBLISH channel1 Hello
(integer) 1
We released a message "Hello" to Channel1, with a return value of 1, indicating that a consumer received a message. At this point, our consumer client watchdog heard the message and output the content
1) "Message"
2) "Channel1"
3) "Hello"
Subscribe by Rules
In addition to the Subscribe command, Redis also provides the Psubscribe command, which supports subscribing to channels through BLOB-style wildcard formats. We open a new REDIS-CLI client and listen to the channel* queue through the Psubscribe command
Redis 127.0.0.1:6379> psubscribe channel*
Reading messages ... (Press Ctrl-c to quit)
1) "Psubscribe"
2) "channel*"
Then open the Producer client and post messages to Channel1 and Channel2 channels, respectively.
Redis 127.0.0.1:6379> PUBLISH channel1 Hello
(integer) 1
redis 127.0.0.1:6379> PUBLISH channel2 Hello
(integer) 1
At this point, our consumer client supervisor hears two messages and then outputs
1) "Pmessage"
2) "channel*"
3) "Channel1"
4) "Hello"
1) "Pmessage"
2) "channel*"
3) " Channel2 "
4)" Hello "
As can be seen from the consumer's output, REDIS returns the channel that Psubscribe listens to, the specific channel that receives the message, and the message content.