search
HomeDatabaseRedisA brief discussion on the implementation methods of message queue and delayed message queue in Redis

How does Redis implement message queue and delayed message queue? The following article will introduce to you the implementation methods of message queue and delayed message queue in Redis. I hope it will be helpful to you!

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

When it comes to redis, more people may think of it as a cache. In fact, redis can also implement some simple message queue purposes. We can use the list data structure to implement the queue. . [Related recommendations: Redis Video Tutorial] Several commands of

list

lpush (left push)

by queue Store it in from the left side

rpush (right push)

Store it from the right side of the queue

lpop (left pop)

Take it out from the left side of the queue

rpop (right pop)

Take it out from the right side of the queue

The above four commands can let list help us implement queues or stacks. The characteristics of queues are advanced First out, the characteristic of the stack is first in, last out,

So the queue implementation can use lpush rpop or rpush lpop,

The stack implementation is lpush lpop or rpush rpop.

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Use command demonstration queue

Producer publishes message

First we use rpush to add five elements to a queue called notify-queue, namely 1 2 3 4 5, which is to publish messages as a producer

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Consumer consumption news

Since the producer uses rpush, the consumer must use lpop. You can see the picture below. We keep informing -queue consumes messages in order, from 1 to 5, and reads them in order. In the end, there are no messages in the queue, and the pop-up is always empty

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Empty polling problem

When using lpop to consume messages above, you can see that after the message is consumed, every time we go to pop, we read an empty message,

The above is a manual execution command, but if the written code program keeps popping data (pulling data), it will cause empty polling (useless reading),

will both pull high It increases the CPU consumption of the client, increases the QPS of redis, and is still a useless operation. These useless operations may cause other clients' access to redis to become slow to respond.

Solution A (hibernation)

Since empty polling will cause higher resource consumption on both the client and redis, then We can let the client sleep for 1s when receiving empty data, and then pull the data after 1s, which can reduce consumption

Thread.sleep(1000)

This solution also has flaws, that is, the delay in message consumption increases. If there is only one consumer, the delay is 1s. That is, after empty polling, it happens to be sleeping, but at this time, a message happens to come. You still have to wait until 1s to wake up before consumption.

If there are multiple consumers, since the sleep time of each consumer is staggered, some latency will be reduced, but is there a better way? Method that can achieve almost 0 latency?

Solution B (Blocking Read)

There are actually two commands in redis about queue data fetching, namely blocking reading,

blpop (blocking left pop)

brpop (blocking right pop)

Blocking read will enter a dormant state when there is no data in the queue. Once a message comes, Then react immediately and read the data, so using blpop/brpop to replace lpop/rpop can solve the problem of message delay.

Continue to queue 3 attributes, 6, 7, 8

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Use blpop to read the queue. The last parameter is the waiting time for blocking reading. If there is no message after this time, nil will be returned. At this time, you can continue to repeat the blpop operation.

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

The problem of automatic disconnection of idle connections for blocking reads

When the client uses blocking reading, if the blocking time is too long, The service will generally treat it as an idle connection and actively disconnect it to reduce useless connections occupying resources. At this time, the client will throw an exception,

So please note that when the client uses blocking reading, It is necessary to catch exceptions and handle them accordingly, such as retrying.

java client implements message queue

The idea is the same as above, except that the command line client redis-cli is changed into java language. One thread or multiple threads publish rpush,

Another thread or threads perform blpop consumption. The completed code is at: https://github.com/qiaomengnan16/redis-demo/tree/main/redis-queue

Publisher

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Subscriber

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

##Implementation ideas of delay queue

The delay queue refers to a period of time after the message is sent, and then consumed by the consumer, rather than after the message is sent, the consumer can read it immediately,

zset can help us do this. First, zset can be sorted by score, and score can store a timestamp. So every time we publish a message, we use the current timestamp plus the delayed timestamp,

When the consumer then retrieves the message, it intercepts the zset data and obtains the message that has satisfied the current time (that is, the data with a score less than or equal to the current timestamp is obtained. The score less than or equal to the current timestamp means that the message has reached the time. If it is larger, it means you have to wait for a while before consumption).

Key commands zadd (publisher), zrangebyscore (subscriber), zrem (subscriber deletes after consuming data)

Command implementation

We used zadd to add 4 pieces of data, which are data that can be consumed after 1, 2, and 3 seconds (pseudo-speak, this is actually just a score), and there is also kafka that can be consumed after 10 seconds.

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

If it is now the third second, we take the data in zset that is greater than or equal to 1 second and less than or equal to 3 seconds, because the data in this interval is exactly what we can consume Yes, you can see that we have taken out 3 pieces of data that meet the conditions.

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

If you can only consume one piece of data at a time, you can add a limit restriction. You can see The following figure takes out the first data that can be consumed. redis

A brief discussion on the implementation methods of message queue and delayed message queue in Redis

# Also note that it is different from lpop/ and blpop of list (they will automatically delete the data in the original queue when they pop up. data),

Although the data is obtained, if you do not use zrem to delete it, this data will still be read by others, because it still exists in zset,

But zrem It may happen that it has been deleted (consumed) by others first, so the code also needs to judge whether the return value of zrem is greater than 0 to determine whether we have successfully preempted this message, and then consume it correctly after success.

Code implementation

Publisher

1A brief discussion on the implementation methods of message queue and delayed message queue in Redis

Subscriber

1A brief discussion on the implementation methods of message queue and delayed message queue in Redis

##Test the delay effect

1A brief discussion on the implementation methods of message queue and delayed message queue in RedisFull code address: https://github.com/qiaomengnan16/redis-demo/tree/main/redis-delayed-queue

##Optimization, using lua to implement

There is a problem in the delay queue implemented above. When using zrem to determine whether to grab the data, it is very likely that it has not been grabbed. If you continue to read like this, you may not be able to grab it for several rounds, and resources are wasted. Therefore, optimization can be carried out through Lua scripts,

Let zrangebyscore and zrem become an atomic operation, which can avoid multi-thread contention and waste of resources that cannot be grabbed.

1A brief discussion on the implementation methods of message queue and delayed message queue in Redis

1A brief discussion on the implementation methods of message queue and delayed message queue in RedisConclusion

Some professional queue middleware will be more complicated to apply and Increase operation and maintenance costs, such as RabbitMQ. Before sending a message, you need to create an Exchange switch and then create a Queue. Then the Exchange and the Queue need to be bound. When sending a message, you must specify the routing-key to match the Exchange and finally reach the Queue.

If the scenario is simple, you can use redis to implement a queue, but it should be noted that redis does not have the characteristics of a professional queue, and there is no guarantee of ack, which means that the message is unreliable. After the consumption fails, it will be gone. If you need 100% reliability, you still need to use professional queue middleware and other mechanisms such as ack as a guarantee.

For more programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of A brief discussion on the implementation methods of message queue and delayed message queue in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

redis error什么意思redis error什么意思Jun 17, 2019 am 11:07 AM

redis error就是redis数据库和其组合使用的部件出现错误,这个出现的错误有很多种,例如Redis被配置为保存数据库快照,但它不能持久化到硬盘,用来修改集合数据的命令不能用。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools