A priority queue is an abstract data type such as a FIFO queue and a stack data structure. The difference is that each element is associated with a "priority". Elements with high priority are treated with precedence over elements with lower priority levels. This article explains how to implement a priority queue based on the Redis sorted set data type.
The elements in the SORTED set are associated with a score that can be ordered by score.
The basic operation of the priority queue is implemented as follows: Is_empty: Check if the queue is empty. This can be accomplished using the EXISTS command.
EXISTS priority_queue
Insert_with_priority: Adds an element associated with "priority" to the queue. The direct use of the ZADD command can be implemented. The Zadd command also has a range of options to support more complex operations.
Zadd Priority_queue Priority Member
Pull_highest_priority_element: Removes the element with the highest priority from the queue and returns. There are no direct commands in Redis to support this operation. This article uses a Redis script for this operation. Redis Scripts support transactional atomicity and isolation, so the following script does not create a race condition. For specific transaction characteristics, please refer to https://redis.io/topics/transactions.
Local items = Redis.call (' Zrangebyscore ', keys[1], '-inf ', ' +inf ', ' LIMIT ', 0, 1)
if Next (items) ~= Nil then
Redis . Call (' Zrem ', keys[1], unpack (items))
End
return items
You can also implement multiple elements of a pop by overwriting the above script.