Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Redis publish / subscribe Model

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Redis publish / subscribe model case analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Redis publish / subscribe model case analysis" bar!

Redis publish / subscribe applications

Publish and subscribe (pub/sub) is a message communication pattern whose main purpose is to decouple the coupling between message publishers and message subscribers, which is similar to the Observer pattern in the design pattern. Pub / sub solves not only the direct code-level coupling of publishers and subscribers, but also the coupling of the two in physical deployment. As a pub/sub server, redis acts as a function of message routing between subscribers and publishers. Subscribers can subscribe to the message type they are interested in through the subscribe and psubscribe commands from redis server, which redis calls a channel. When a publisher sends a specific type of message to redis server through the publish command. All client that subscribe to this message type will receive this message. The message delivery here is many-to-many. A client can subscribe to multiple channel or send messages to multiple channel.

Let's start with the basic commands:

PSUBSCRIBE pattern [pattern...] # subscribe to one or more channels that match a given mode; PUBSUB subcommand [argument [argument...]] # View the status of the subscription and publishing system; PUBLISH channel message # sends information to the specified channel; PUNSUBSCRIBE [pattern [pattern...]] # unsubscribe to all channels of a given mode SUBSCRIBE channel [channel...] # subscribe to a given channel or channels; UNSUBSCRIBE [channel [channel...]] # means to unsubscribe from a given channel

As you can see from the redis manual, the "publish and subscribe" mode has only six commands. Let me explain them one by one.

SUBSCRIBE

Subscribe to information for a given channel or channels.

SUBSCRIBE channel [channel...]

Judging from the above official explanation, its play is a bit like listening to the radio in real life. What should we do if we want to listen to the radio? It must be FM. Only on the right channel can we hear good programs, so subscribe must first subscribe to a channel (channel). Let me give an example, open two client and subscribe to msg, such as the following:

Root@localhost:~ # redis-cli-p 6379127.0.0.1 SUBSCRIBE msgReading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "msg" 3) (integer) 1 rootworthy localhost redis-cli ~ # redis-cli-p 6379127.0.0.1 msg 6379 > SUBSCRIBE msgReading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "msg" 3) (integer) 1

SUBSCRIBE can also subscribe to multiple channels, so the information it receives may come from multiple channels.

PUBLISH

Up to now, both subscibe have been monitoring the msg channel. Next, if anything comes out of the msg channel, it will be picked up by the subscribe. Let's take a look at how to use this command in the redis manual.

Sends the information message to the specified channel channel.

PUBLISH channel message

The demonstration is as follows:

See, after publish sent messages on the msg channel, it was monitored by subscribe and then printed out separately. well, so far, this is the most basic publish and subscribe model, isn't it very simple? Actually? It's that simple, but sometimes we still have such a requirement, that is, can I vaguely match key? For example, it is required to subscribe to all channels prefixed with china, and if this can be done, it is really amazing. If I answer, of course, the powerful Redis will do this naturally, and the command it provides is: PSUBSCRIBE.

PSUBSCRIBE

Subscribe to one or more channels that match a given pattern, each pattern as a match, for example, it matches all channels starting with it (it.news, it.blog, it.tweets, etc.), and news.* matches all channels with news. The opening channel (news.it, news.global.today, etc.), and so on.

PSUBSCRIBE pattern [pattern...]

Seeing the explanation above, you may be thinking to yourself that this is a regular match. And the prefix "P" means Pattern, right? then I'll subscribe to all the channel with the prefix china.

Of course, PSUBSCRIBE can also accept multiple parameters to match multiple patterns. After reading a small example, you should have a perceptual understanding of the function of pub/sub. It is important to note that when a connection goes through the subscribe or psubscribe subscription channel, it enters subscription mode. In this mode, no other commands can be sent except subscribing to additional channels or exiting subscription mode with unsubscribe or punsubscribe commands. In addition, use the psubscribe command to subscribe to multiple wildcard channels, and if a message matches multiple channel patterns, you will receive the same message multiple times.

Redis's pub/sub is still a little too thin (the implementation takes only 150 lines of code). There is not much support for this convenience in security, authentication, and reliability.

Redis publish / subscribe mechanism

When a client sends a message to a subscriber through the PUBLISH command, we call the client a publisher.

When a client uses SUBSCRIBE or PSUBSCRIBE commands to receive information, we call the client a subscriber.

To decouple the relationship between the publisher (publisher) and the subscriber (subscriber), Redis uses channel as the intermediary between the two-the publisher publishes the information directly to the channel, while the channel is responsible for sending the information to the appropriate subscriber. There is no relationship between the publisher and the subscriber and they are not aware of each other's existence:

Now that you know the mechanism for publishing and subscribing, you can start to study the specific implementation, starting with Redis's subscription commands.

Implementation of SUBSCRIBE command

As mentioned earlier, Redis leaves all the tasks of receiving and sending messages to channel, and all channel information is stored in the redisServer structure:

Struct redisServer {/ / omitted. Dict * pubsub_channels; / / Map channels to list of subscribed clients / / omit.}

Pubsub_channels is a dictionary, the key of the dictionary is a channel, and the value of the dictionary is a linked list, which holds all the clients that subscribe to this channel.

For example, if in a redisServer instance there is a channel called news, which is subscribed by both client_123 and client_456 clients, the redisServer structure should look like this:

As you can see, the key to implementing the SUBSCRIBE command is to add the client to the subscription list of a given channel.

Implementation of PSUBSCRIBE command

In addition to directly subscribing to a given channel, you can also subscribe to a pattern (pattern) using PSUBSCRIBE, which is equivalent to subscribing to all channel that match that pattern.

Similar to the redisServer.pubsub_channels attribute, the redisServer.pubsub_patterns attribute is used to hold all subscribed schemas, but unlike pubsub_channels, pubsub_patterns is a linked list (not a dictionary):

Struct redisServer {/ / omitted. List * pubsub_patterns; / / A list of pubsub_patterns / / omit.}

Each node of the pubsub_patterns is an instance of the pubsubPattern structure that holds the subscribed pattern and the client clients that subscribe to the pattern:

Typedef struct pubsubPattern {redisClient * client; robj * pattern;} pubsubPattern

For example, suppose that in an redisServer instance, a schema called news.* is subscribed by both the client client_789 and client_999, then the redisServer structure should look like this:

Now you can see that the key to implementing the PSUBSCRIBE command is to add client and subscription patterns to the redisServer.pubsub_patterns.

Thank you for reading, the above is the "Redis publish / subscribe model case analysis" content, after the study of this article, I believe you have a deeper understanding of the Redis publish / subscribe model example analysis of this problem, the specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report