Redis-implement priority queue

Redis implements the queue function, generally by using the LPUSH command and the BRPOP command to complete it. However, queues also have their own priorities. If there are multiple queues but there is only one consumer, how to achieve the priority of consumption?

Basic syntax of BRPOP

BLPOP LIST1 LIST2 .. LISTN TIMEOUT 

第一个是键名,第二个是超时时间,单位是秒,如果列表为空或者超过了超时时间还没获取到新元素,就返回一个nil,否则返回一个含有两个元素的列表,第一个元素是被弹出元素所属的key,第二个元素是被弹出元素的值。

超时时间为"0",表示不限制等待的时间。

It can be found that the first parameter supports multiple, so the BLPOP command can actually receive multiple keys at the same time. When the BLPOP command monitors multiple keys at the same time, as long as there is an element in one key, the element will pop up. If multiple keys have no elements, it will block. Of course, if there are elements in multiple keys, then the elements in the key will be popped up in the order of the keys defined by the BLPOP command, which indirectly realizes the priority of the queue.

Redis implementation of priority queue operation example

First open two redis-cli instances, the port is 6380, one as a consumer, one as a producer, as follows:

Insert picture description here

Here, let the producer produce several messages into the three queues, and the consumer will not open it temporarily, otherwise the effect will not be obvious, as follows:

Put the following 3 elements in the queue:1 key:
Insert picture description here

Put the following 2 elements in the queue:2 key:
Insert picture description here

Place the following 1 element in the queue:3 key:
Insert picture description here

Then let the consumer use the BRPOP command to monitor the above 3 keys, try to take out the elements, and see the order in which the elements are popped:
Insert picture description here
From the output result, the elements are popped in order, and only the elements in the first key are almost consumed. When it is exhausted, the elements in the second key will be popped up, and then the elements will be fetched in order until there are no elements in the blocking state.

to sum up

Through the BRPOP command to monitor multiple keys at the same time, the priority queue function can be realized.

Guess you like

Origin blog.csdn.net/weixin_38106322/article/details/108525044