Redis study notes publish and subscribe
This article brings you relevant knowledge about Redis, which mainly introduces issues related to publish and subscribe. Redis publish and subscribe (pub/sub) is a message communication mode: send The publisher (pub) sends the message, and the subscriber (sub) receives the message. Let's take a look at it. I hope it will be helpful to everyone.
Recommended learning: Redis video tutorial
Redis publish and subscribe (pub/sub) is a message communication model : The sender (pub) sends the message, and the subscriber (sub) receives the message.
Redis clients can subscribe to any number of channels.
Subscribe/publish message graph:
The first object: the message sender. Second object: channel. The third object: message subscriber.
The following figure shows the relationship between channel channel1 and the three clients that subscribe to this channel - client2, client5 and client1:
When a new message is sent to channel channel1 through the PUBLISH command, this message will be sent to the three clients that subscribe to it:
Command | Description |
---|---|
Publish channel message Command | Send the message to specified channel. |
SUBSCRIBE channel [channel …] | Subscribe to the information of one or more given channels. |
UNSUBSCRIBE channel [channel …] | refers to unsubscribing from a given channel. |
[PUNSUBSCRIBE pattern [pattern …]] | Unsubscribe from all channels of the given pattern. |
[PUBSUB argument [argument …] | View the subscription and publishing system status. |
PSUBSCRIBE pattern [pattern …] | Subscribe to one or more channels that match the given pattern. |
Test
Subscriber:
127.0.0.1:6379> subscribe mianbao # 订阅频道 mianbao Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "mianbao" 3) (integer) 1 # 等待读取推送的消息 1) "message" # 消息 2) "mianbao" # 频道 3) "hello" # 消息内容 1) "message" 2) "mianbao" 3) "hello redis"
Sender:
127.0.0.1:6379> publish mianbao "hello" # 发送消息到频道 (integer) 1 127.0.0.1:6379> publish mianbao "hello redis" (integer) 1
Principle:
Redis is implemented using C. By analyzing the pubsub.c file in the Redis source code, we can understand the underlying implementation of the publishing and subscription mechanism, and deepen our understanding of Redis.
Redis implements publishing and subscribing functions through commands such as PUBLISH, SUBSCRIBE and PSUBSCRIBE.
After subscribing to a channel through the SUBSCRIBE command, a dictionary is maintained in redis-server. The keys of the dictionary are channels, and the value of the dictionary is a linked list. All subscriptions are stored in the linked list. The client of the channel. The key to the SUBSCRIBE command is to add the client to the subscription list of a given channel.
Send a message to the subscriber through the PUBLISH command. The redis-server will use the given channel as the key, search the linked list of all clients that subscribe to this channel in the channel dictionary it maintains, and traverse the linked list. , publish the message to all subscribers.
Pub/Sub literally means publishing (Publish) and subscription (Subscribe). In Redis, you can set up message publishing and message subscription for a certain key value. When a key value is used, After a message is published, all clients that subscribe to it will receive the corresponding message. The most obvious use of this function is as a real-time messaging system, such as ordinary instant chat, group chat and other functions.
For slightly more complex scenarios we will use message middleware: RabbitMQ, RocketMQ, ActiveMQ, kafka
Recommended learning: Redis video tutorial
The above is the detailed content of Redis study notes publish and subscribe. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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: 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.

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.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

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.

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information
