preface
The 16th in the Redis series, Redis’s
pub/sub
(Publish subscribe model), although this was in the first Redis seriesI met RedisIt is mentioned that this is not normally used for message queuing systems. However, Redis itself supports this functionality, so it is necessary to learn a lot. On the one hand, assuming that the company does not use the special message queue middleware, then you can come up with Redis implementation. On the other hand, this can be in the follow-up interview can be appropriate to the interviewer to talk about, some interviewers also have the initiative to ask this (I met a strong man, at that time was a cute new, although now is, what do not understand, directly to me the whole thing, I don’t interview a junior it). Now you are asking me to try, ha ha ha……
An overview of the
Before publishing/subscribing, have you been asked the difference between publish/subscribe and observer? At first you might think these two things are similar, but there are differences
Observer model
Concept: A target object (observed) manages all observer objects that depend on it, and automatically notifies dependent objects in its own state. The observer model belongs to the behavioral model.
In the childhood of the post-90s generation, we would go to the fields to make loach in small groups. (Children from the countryside have no toys, they can only play in mud, but we are happy.) But mom always asks to be careful before going, and almost goes home for dinner. As a result, happy time is always short. Noon soon arrived, this time will pay attention to one thing, “lunch is ready, whether it is time to go home for dinner”. Is there a cell phone (maybe, but also can’t afford), so what to do. As witty as you. We always have to run home every once in a while to ask if the meal is ready, go out to play when it is not, and wash our hands to eat when it is ready (like pulling data with JS polling interface). Slowly, mobile phones became a must-have. We don’t have to run back to mom to see if dinner is ready. When it’s time for dinner, your mom will always call you to tell you that dinner is ready and it’s time to go home for dinner (event-driven, triggering push notifications). Good brothers, this is not consistent with the observer model. The observed (mom), the observer (us playing in the mud), the event (whether Mom cooked the meal), and the list of observers maintained by the observed (me and my little brother).
Publish and subscribe model
Concept:Publish/subscribe
Is a message communication pattern in which the sender (publisher) of a message does not direct the message to a specific receiver (subscriber). Instead, they divide the published messages into different categories without knowing which subscribers might exist and which categories they might be interested in. Similarly, subscribers can express interest in one or more categories and only receive messages of interest. Redis provides a basis forPublish/subscribe
In this mode, the publisher and subscriber do not communicate directly, and the publisher client communicates to the specifiedchannel
(channel) publishes a message, which is received by every client that subscribes to the channel, as shown below
I third brother (subscriber) often in the small broken site of the dance area (category) learning to dance, third brother can subscribe to any number of interested channels (dancing, two yuan), but also do not care who published this channel (as long as can learn to dance on the line), only receive their interested channel news. On the other hand, small sites don’t need to know who is following which channels, just update the content of the corresponding channels.
contrast
- The observer is not static. Not everyone goes home for lunch every day. Only the people who tell mom they’re coming home for lunch get the call. Because of the variability of the observer, a list needs to be maintained by the observer.
- Observer mode makes it easy to accomplish goals. There is no need for the observer to constantly look around to see what happens, and there is no need for the observed to ask the observer more than once. Only the observer needs to join or leave the list in advance, it can be accurately notified by the observed events. Speaking of which, wechat subscription account is a realization of the observer mode.
Publish/subscribe
Unaware of each other’s existence. You need a third-party component, called a message mediator, that connects subscribers and publishers, and that filters and allocates all incoming messages.
The command
Redis mainly provides commands for publishing messages, subscribing to channels, unsubscribing, subscribing to patterns, and unsubscribing.
1 Releasing Messages
Push a message to dance channel
## format: channel, message
publish channel message
## Publish a message to dance channel, return the result is the number of subscribers, if there is no return 0
127.0.0.1:6379> publish channel:dance "put your hands!"
(integer) 0
Copy the code
2 Subscribe Message
A subscriber can subscribe to one or more channels, and the following actions subscribe to a channel for the current client.
## format: channel
subscribe channel [channel .]
127.0.0.1:6379> subscribe channel:dance
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel:dance"
3) (integer) 1
Create a new client to send messages to a channel
127.0.0.1:6379> publish channel:dance "are your ok"
(integer) 1
Switch to the subscriber client and receive the following message
127.0.0.1:6379> subscribe channel:dance
Reading messages... (press Ctrl-C to quit)
...
1) "message"
2) "channel:dance"
3) "are your ok"
Copy the code
Note that the newly opened subscription client cannot receive previous messages from this channel, because Redis does not persist published messages. Compared to many professional message queuing systems (such as Kafka and RocketMQ), Redis publishes and subscribing a little rough. In contrast to many professional message queuing systems (such as Kafka and RocketMQ), Redis is a bit rough in publishing and subscribing. For example, the client is in the subscribing state after executing the subscribing command. Only subscribe, psubscribe, unsubscribe, and punsubscribe commands can be received.
3 Unsubscribe
The client can cancel the subscription to a specified channel by using the unsubscribe command. After the unsubscribe is successful, the client will not receive any message from the channel
## format: channel
unsubscribe [channel [channel .]]
## Publish a message to dance channel, return the result is the number of subscribers, if there is no return 0
127.0.0.1:6379> unsubscribe channel:dance
1) "unsubscribe"
2) "channel:dance"
3) (integer) 0
Copy the code
4 Subscribe and unsubscribe by pattern
In addition to the subcribe and unsubscribe commands, the Redis command also supports the glob style (simplified regular expressions under the shell) subscribe command psubscribe and unsubscribe command punsubscribe.
## format pattern
psubscribe pattern [pattern...]
punsubscribe [pattern [pattern .]]
Subscribe to channels that start with Java
127.0.0.1:6379> psubscribe Java*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "Java*"
## Cancel subscriptions that start with Java
127.0.0.1:6379> punsubscribe Java*
Reading messages... (press Ctrl-C to quit)
1) "punsubscribe"
2) "Java*"
3) (integer) 0
Copy the code
5 Querying Subscriptions
Check active channels
Active channel means that the current channel has at least one subscriber, where [Pattern] can specify a specific pattern
# # format
pubsub channels [pattern]
## Query active subscriptions
127.0.0.1:6379> pubsub channels channel:*d*
1) "channel:dance"
2) "channel:durid"
Copy the code
Check channel subscriptions
# # format
pubsub numsub [channel .]
# # subscriptions
127.0.0.1:6379> pubsub numsub channel:dance
1) "channel:dance"
2) (integer) 1
Copy the code
View the number of mode subscriptions
Number of subscriptions by schema
# # format
pubsub numpat
# # number
127.0.0.1:6379> pubsub numpat
(integer) 1
Copy the code
The principle of analytic
To subscribe to
In the underlying structure of Redis, one is defined in the Redis server structurepubsub_channels
The dictionary, which maintains the correspondence between channels and subscribers, adds the corresponding client information to the end of the linked list every time a client adds a subscription.
release
Release the message now according to chanel to find the corresponding subscribers linked list, and then traverse send a message on the OK.
Usage scenarios
- IM real time chat room
- Announcement/bulletin board, system message notification
- Wechat official accounts and similar scenes
- System service logic functions are decoupled
conclusion
There is a distinction between publish and subscribe and observer mode, so you can understand that the interview scenario is often encountered. In addition, Redis’s publish-subscribe functionality is not as powerful as in the middle of message queues like RocketMQ and Kafka, but it is simple. I don’t think good brothers use this for message queues.
That’s the end of this issue. Welcome to leave your comments in the comments sectionAsk for attention, ask for likes
Next post: Redis GEO, you will never use it