Redis (5)-Redis publish and subscribe

1Redis publish and subscribe

Redis publish and subscribe (pub/sub) is a message communication mode: the sender (pub) sends a message, and the subscriber (sub) receives the message. WeChat, Weibo, follow system!
Redis clients can subscribe to any number of channels.

Subscribe/publish message graph

Insert picture description here
Insert picture description here
Insert picture description here

command

These commands are widely used to build instant messaging applications, such as online chat rooms and real-time broadcasts, real-time reminders, etc.
Insert picture description here

test

Insert picture description here

Subscriber

127.0.0.1:6379> SUBSCRIBE kuangshenshuo  # 订阅一个频道 kuangshenshuo Reading messages... (press Ctrl-C to quit) 
1) "subscribe" 
2) "kuangshenshuo"
3) (integer) 1
# 等待读取推送的信息 
1) "message"  # 消息 
2) "kuangshenshuo"  # 那个频道的消息
3) "hello,kuangshen"  # 消息的具体内容

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

Sender

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

principle

Redis is implemented in C. By analyzing the pubsub.c file in the Redis source code, we can understand the underlying implementation of the publish and subscribe mechanism, so as to deepen our understanding of Redis.
Redis implements publish and subscribe functions through commands such as PUBLISH (publish), SUBSCRIBE (subscribe) and PSUBSCRIBE.

After subscribing to a channel through the SUBSCRIBE command , a dictionary (k, v) is maintained in redis-server, and the keys of the dictionary are channels! The value of the dictionary is a linked list in which all clients subscribed to this channel are stored . The key to the SUBSCRIBE command is to add the client to the subscription list of a given channel. Send messages to subscribers
Insert picture description here
through the PUBLISH command . Redis-server uses the channel as a key, looks up all the client linked lists subscribed to this channel in the channel dictionary it maintains, traverses this list, and publishes the message to all subscribers.

Pub/Sub literally means Publish and Subscribe. In Redis, you can set a key value for message publishing and message subscription. When a message is sent on a key value, all subscriptions Its clients will receive the corresponding message. The obvious usage of this function is to be used as a real-time cancellation system, such as ordinary instant chat, group chat and other functions.
Use scenario:
real-time message system!
Fact chat! (The channel can be used as a chat room, just show the information back to everyone!)
Subscribe and follow the system are all possible! For slightly more complex scenarios, we will use the message middleware MQ

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/113913255