Reputation: 1565
Is there good way to support pop members from the Redis Sorted Set just like the api LPOP of the List ?
What I figured out for poping message from the Redis Sorted Set is using ZRANGE +ZREM , however it is not thread security and need the distributed lock when multi threads accessing them at the same time from the different host.
Please kind suggesting if there is better way to pop the members from the Sorted Set?
Upvotes: 3
Views: 3694
Reputation: 1064044
In Redis 5.0 or above, you can use [B]ZPOP{MIN|MAX}
key [count] for this scenario.
The MIN
version takes the item(s) with the lowest scores; MAX
takes the item(s) with the highest scores. count defaults to 1, and the B
prefix blocks until the data is available.
Upvotes: 5
Reputation: 23021
You can write a Lua script to do the job: wrap these two commands in a single Lua script. Redis ensures that the Lua script runs in an atomic way.
local key = KEYS[1]
local result = redis.call('ZRANGE', key, 0, 0)
local member = result[1]
if member then
redis.call('ZREM', key, member)
return member
else
return nil
end
Upvotes: 4