Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can I use Redis db to create Priority queues and the priority is set according to the value of the key in the data set

Tags:

java

redis

queue

I am new to Redis. I want to use priority queues in Redis via Java client. I will have a set of key value pairs. And use this as a priority queue.

The data set contains keys and its corresponding values. example [a:1,b:1,c:1]. The value field will represent the number of times the key is present in the data set. If another key "a" is inserted into the data set, then it becomes [a:2,b:1,c:1].

Here comes the priority. The most of keys present in the set will be of highest priority, in the example its [a], and it should be at the top of the queue. So when I pop the queue, the element with highest priority should pop out.

Also if the data set looks like this [a:2,b:2,c:2], then I want to pick the random one to pop out of the queue.

Since my data set will be of key, value pair I want to use Redis[you may suggest a better one].

like image 974
Balu Avatar asked Dec 06 '25 09:12

Balu


1 Answers

It should be possible to implement this via Redis sorted sets and Lua scripts. Sorted sets are set of elements ordered by a score, but the score can be updated dynamically. One way to update the score of a sorted set, is to increment its scopre via ZINCRBY, this corresponds to what you are trying to do AFAIK. The element will be automatically moved in the right place according to the incremented score. Then by using the other sorted sets commands you can simulate popping from the sorted set by consuming the element, if this is the semantics you want.

like image 111
antirez Avatar answered Dec 07 '25 23:12

antirez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!