Home Database Redis How to implement message queue based on redis

How to implement message queue based on redis

Nov 26, 2019 am 10:29 AM
redis

How to implement message queue based on redis

Message Queue, Message Queue, is often used to solve resource consistency problems in concurrent systems, improve peak processing capabilities, and ensure the orderliness, recoverability, and must-delivery of messages. , decouple applications, or implement asynchronous communication, etc. (Recommended learning: Redis video tutorial)

There are many MQ applications on the market (for example: Kafka, RabbitMQ, Disque), and they can also be implemented based on Redis, which is more typical The solutions include:

Implementation of LPUSH BRPOP based on List

PUB/SUB, subscription/publishing mode

Implementation based on Sorted-Set

Implementation based on Stream type

In the use of message queues, there are producers and consumers. Producers are responsible for generating messages, and consumers are responsible for processing messages.

Production refers to putting messages into the message queue.

Consumption refers to reading and processing messages. Usually after a message is consumed, it should be deleted from the message queue.

How to implement message queue based on redis

Implementation of LPUSH BRPOP based on List

The typical command is:

LPUSH,将消息队列
BRPOP,从队列中取出消息,阻塞模式
Copy after login

is a typical solution based on FIFL queue. Among them, LPUSH is what the producer does, and BRPOP is what the consumer does.

This model has many advantages:

Simple implementation

Reids supports persistent messages, which means that messages will not be lost and can be viewed repeatedly (note Not consuming, just watching and using, LRANGE class instructions).

The order can be ensured, and the LPUSH command can be used to ensure the order of the messages.

Using RPUSH, the message can be placed at the beginning of the queue to achieve the purpose of prioritizing messages and realizing simple messages. Priority queue.

At the same time, there are some disadvantages:

It is more troublesome to do consumption confirmation ACK, that is, there is no guarantee that the consumer will have unprocessed downtime problems after reading. Resulting in unexpected loss of messages. Usually you need to maintain a Pending list yourself to ensure that the message is processed and confirmed.

Cannot do broadcast mode, such as the typical Pub/Discribe mode.

Cannot be consumed repeatedly, once consumed it will be deleted

Group consumption is not supported, you need to solve it yourself at the business logic layer

PUB/SUB, subscription/publishing Pattern

SUBSCRIBE,用于订阅信道
PUBLISH,向信道发送消息
UNSUBSCRIBE,取消订阅
Copy after login

Producers and consumers interact through the same channel (Channel). A channel is actually a queue. There are usually multiple consumers. Multiple consumers subscribe to the same channel. When a producer publishes a message to the channel, the channel will immediately publish the message to each consumer one by one. It can be seen that the channel is a divergent channel for consumers, and each consumer can get the same message. Typical one-to-many relationship.

The typical advantages are:

Typical broadcast mode, a message can be published to multiple consumers

Multi-channel subscription, consumers can Subscribe to multiple channels at the same time to receive multiple types of messages

Messages are sent immediately. The message does not need to wait for the consumer to read. The consumer will automatically receive the message published by the channel

There are also some Disadvantages:

Once the message is published, it cannot be received. In other words, if the client is not online when publishing, the message will be lost and cannot be retrieved

There is no guarantee that the time received by each consumer is consistent

If a message appears on the consumer client The backlog, to a certain extent, will be forcibly disconnected, resulting in unexpected loss of messages. It usually occurs when the production of messages is much faster than the consumption speed

It can be seen that the Pub/Sub mode is not suitable for message storage and message backlog services, but is good at processing broadcast, instant messaging, and instant feedback services.

Implementation based on SortedSet ordered set

ZADD KEY score member,压入集合
ZRANGEBYSCORE,依据score获取成员
Copy after login

The scheme of ordered set is more commonly used when determining the message order ID by yourself, using the Score of the set member as the message ID, guarantees the order, and can also ensure the monotonous increase of the message ID. Usually a timestamp sequence number scheme can be used. The monotonic increase of message ID is ensured, and an ordered message queue can be created by using SortedSet's feature of sorting according to Score.

Compared with the above solution, the advantage is that the message ID can be customized, which is more important when the message ID is meaningful. The disadvantages are also obvious. Duplicate messages are not allowed (think of them as collections). At the same time, errors in determining the message ID will lead to errors in the order of the messages.

So, if you don’t need to customize the message ID, this solution seems a bit tasteless...

Implementation based on Stream type

This Stream type redis is In order to implement message queue. Supports core message queue functions such as automatic generation of message ID, group consumption, ACK, message transfer, queue monitoring, etc.

For more Redis-related technical articles, please visit the Redis Getting Started Tutorial column to learn!

The above is the detailed content of How to implement message queue based on redis. 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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
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 configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

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)

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.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

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.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

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.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

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

See all articles