09Redis--publish and subscribe

content

Subscribe/publish message graph:

Order

test

Subscription information:

sender:

scenes to be used:


Redis publish and subscribe (pub/sub) is a message communication mode : the sender (pub) sends messages, and the subscribers (sub) receive messages - the attention system of WeChat and Weibo

Redis clients can subscribe to any number of channels

Subscribe/publish message graph:

  • message publisher
  • channel
  • message subscriber

The following figure is the channel channel1, and the relationship between the three clients that subscribe to this channel - cilent2, cilent5 and cilent1

When a message is sent to channel channel1 through the Publish command, the message will be sent to the three clients that subscribe to it

Order

Common commands for redis publish and subscribe:

serial number Command and Description
1 PSUBSCRIBE pattern  [pattern ...]  Subscribe to one or more channels matching the given pattern.
2 PUBSUB subcommand [argument [argument …]]  View subscription and publishing system status.
3 PUBLISH channel message  sends information to the specified channel.
4 PUNSUBSCRIBE [pattern [pattern ...]]  Unsubscribe from all channels for the given pattern.
5 SUBSCRIBE channel  channel ...]  Subscribe to a given channel or channels for information.
6 UNSUBSCRIBE [channel [channel ...]]  means to unsubscribe from the given channel.

test

Subscription information:

127.0.0.1:6379> SUBSCRIBE gh   # 订阅一个频道 gh
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "gh"
3) (integer) 1
# 等待推送消息

1) "message"        # 消息
2) "gh"             # 哪个频道的消息
3) "hello,word"     # 消息的具体内容   

1) "message"
2) "gh"
3) "hello,redis"

sender:

127.0.0.1:6379> PUBLISH gh "hello,word"   # 发布者发布消息到频道
(integer) 1
127.0.0.1:6379> PUBLISH gh "hello,redis"
(integer) 1
127.0.0.1:6379> 

scenes to be used:

1. Real-time message system!

2. Fact Chat! (The channel acts as a chat room, just echo the message to everyone!)

3. It is possible to subscribe and pay attention to the system!

For slightly more complicated scenarios, we will use the message middleware MQ

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324040650&siteId=291194637