【Redis】Pub/Sub

Posted by 西维蜀黍 on 2022-01-02, Last Modified on 2024-02-26

Publish/Subscribe Pattern

Refer to https://swsmile.info/post/publish-subscribe-pattern/

Pub/sub in Redis

SUBSCRIBE, UNSUBSCRIBE and PUBLISH implement the Publish/Subscribe messaging paradigm where (citing Wikipedia) senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Rather, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be. Subscribers express interest in one or more channels, and only receive messages that are of interest, without knowledge of what (if any) publishers there are. This decoupling of publishers and subscribers can allow for greater scalability and a more dynamic network topology.

Demo

Publisher

redis-cli -h 192.168.18.129
192.168.18.129:6379> ping
PONG
192.168.18.129:6379> PUBLISH channel1 111
(integer) 2
192.168.18.129:6379> PUBLISH channel1 222
(integer) 2
192.168.18.129:6379>

Subscriber 1

redis-cli -h 192.168.18.129
192.168.18.129:6379> SUBSCRIBE channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "111"

1) "message"
2) "channel1"
3) "222"

Subscriber 2

redis-cli -h 192.168.18.129
192.168.18.129:6379> SUBSCRIBE channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "111"

1) "message"
2) "channel1"
3) "222"

Reference