Table of Contents
Redis publish/subscribe application
Redis publish/subscribe mechanism
SUBSCRIBE命令的实现
PSUBSCRIBE命令的实现
Home Database Redis Redis publish/subscribe model example analysis

Redis publish/subscribe model example analysis

May 27, 2023 pm 09:29 PM
redis

Redis publish/subscribe application

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

Let’s start with the basic commands:

PSUBSCRIBE pattern [pattern ...]              #订阅一个或多个符合给定模式的频道;PUBSUB subcommand [argument [argument ...]]   #查看订阅与发布系统状态;PUBLISH channel message                       #将信息发送到指定的频道;PUNSUBSCRIBE [pattern [pattern ...]]          #退订所有给定模式的频道;SUBSCRIBE channel [channel ...]               #订阅给定的一个或多个频道的信息;UNSUBSCRIBE [channel [channel ...]]           #指退订给定的频道;
Copy after login

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

SUBSCRIBE

Subscribe to information from a given channel or channels.

SUBSCRIBE channel [channel ...]
Copy after login

Judging from the official explanation above, its gameplay is a bit like listening to the radio in real life. What do we have to do if we want to listen to the radio? It must be FM. Only on the correct channel can we listen to good programs. So to subscribe, we must first subscribe to a channel. Let me give an example below. Open two clients and subscribe to the msg channel respectively. For example, as follows:

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

root@localhost:~ # redis-cli -p 6379127.0.0.1:6379> SUBSCRIBE msg
Reading messages... (press Ctrl-C to quit)
1) "subscribe"2) "msg"3) (integer) 1
Copy after login

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

PUBLISH

Up to now, these two subscibes are monitoring the msg channel. Next, if there is news coming out of the msg channel, it will definitely be subscribed. Received, let's first look at how to use this command in the redis manual.

Send information message to the specified channel channel.

PUBLISH channel message
Copy after login

The following demonstration:

Redis publish/subscribe model example analysis

See, after publish sends a message on the msg channel, it is monitored by subscribe, and then printed separately. Output, okay, so far, the most basic publish-subscribe model is like this. Isn’t it very simple? Actually? ? ? It's that simple, but sometimes we still have a need, that is, can I fuzzy match the key? For example, it is required to subscribe to all channels with the prefix china. If this can be done, it would be really awesome. . . If I were to answer, it would certainly be that the mighty Redis can definitely do it, it provides the command PSUBSCRIBE.

PSUBSCRIBE

Subscribe to one or more channels that match the given pattern. Each pattern uses as the matching character. For example, it matches all channels ending with Channels starting with it (it.news, it.blog, it.tweets, etc.), news.* matches all channels starting with news. (news.it, news.global.today, etc.), and so on.

PSUBSCRIBE pattern [pattern ...]
Copy after login

After seeing the above explanation, you may be thinking, isn’t this just regular matching? . . Next, I will subscribe to all channels with "china" as the prefix, because the prefix "P" stands for "Pattern", right? .

Redis publish/subscribe model example analysis

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

Although the pub/sub implementation of Redis only requires 150 lines of code, its functions may not be complete enough. There is not much support in terms of security, authentication, and reliability.

Redis publish/subscribe mechanism

When a client sends information to subscribers through the PUBLISH command, we call the client a publisher.

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

In order to decouple the relationship between publisher and subscriber, Redis uses channel as the intermediary between the two - the publisher publishes information directly to the channel, The channel is responsible for sending information to the appropriate subscribers. There is no mutual relationship between the publisher and the subscriber, and they do not know the existence of each other:

Redis publish/subscribe model example analysis

知道了发布和订阅的机制之后,接下来就可以开始研究具体的实现了,我们从Redis的订阅命令开始说起。

SUBSCRIBE命令的实现

前面说到,Redis将所有接受和发送信息的任务交给channel来进行,而所有channel的信息就储存在redisServer这个结构中:

struct redisServer {
  // 省略 ...
  dict *pubsub_channels; // Map channels to list of subscribed clients
  // 省略 ...
};
Copy after login

pubsub_channels是一个字典,字典的键就是一个个channel,而字典的值则是一个链表,链表中保存了所有订阅这个channel的客户端。

举个例子,如果在一个 redisServer 实例中,有一个叫做 news 的频道,这个频道同时被client_123 和 client_456 两个客户端订阅,那么这个 redisServer 结构看起来应该是这样子: Redis publish/subscribe model example analysis

可以看出,实现SUBSCRIBE命令的关键,就是将客户端添加到给定channel的订阅链表中。

PSUBSCRIBE命令的实现

除了直接订阅给定channel外,还可以使用PSUBSCRIBE订阅一个模式(pattern),订阅一个模式等同于订阅所有匹配这个模式的channel 。

和redisServer.pubsub_channels属性类似,redisServer.pubsub_patterns属性用于保存所有被订阅的模式,和pubsub_channels不同的是, pubsub_patterns是一个链表(而不是字典):

struct redisServer {
  // 省略 ...
  list *pubsub_patterns; // A list of pubsub_patterns
  // 省略 ...
};
Copy after login

pubsub_patterns 的每一个节点都是一个 pubsubPattern 结构的实例,它保存了被订阅的模式,以及订阅这个模式的客户客户端:

typedef struct pubsubPattern {
  redisClient *client;
  robj *pattern;
} pubsubPattern;
Copy after login

举个例子,假设在一个 redisServer 实例中,有一个叫做 news.* 的模式同时被客户端client_789 和 client_999 订阅,那么这个 redisServer 结构看起来应该是这样子: Redis publish/subscribe model example analysis

现在可以知道,实现PSUBSCRIBE命令的关键,就是将客户端和订阅的模式添加到redisServer.pubsub_patterns当中。

The above is the detailed content of Redis publish/subscribe model example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to solve data loss with redis How to solve data loss with redis Apr 10, 2025 pm 08:24 PM

Redis data loss causes include memory failures, power outages, human errors, and hardware failures. The solutions are: 1. Store data to disk with RDB or AOF persistence; 2. Copy to multiple servers for high availability; 3. HA with Redis Sentinel or Redis Cluster; 4. Create snapshots to back up data; 5. Implement best practices such as persistence, replication, snapshots, monitoring, and security measures.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

See all articles