Implementing a priority queue using Redis

Source: Internet
Author: User
Tags redis
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.