Redis - is there a blpush

2019-04-13 05:37发布

问题:

For data communication across processes, I intend to use Redis list. The producer pushes to the list, while a set of consumers consume the list contents using BRPOP.

In order to restrict the list growing infinitely in size, I want to restrict the list size to a fixed value (say 10K items). I was surprised to find no equivalent command like BLPUSH or BRPUSH. Is this a deliberately omitted by Redis folks?

So, I assume I have to create a Txn with Watch/multi to check the list size before pushing. Is this the right way, or any better techniques available?

回答1:

I would go for a lua script for this functionality.

LUA that accepts one key (list name), and two arguments, new_element_name and max_size. Return value could be the LPUSH return value or -1 when the list is full.
Here's a script that does this:

if tonumber(ARGV[2]) > redis.call('LLEN', KEYS[1]) then
    return redis.call('LPUSH', KEYS[1], ARGV[1])  end 
return -1

You should load it once with SCRIPT LOAD:

cat blpush.lua | redis-cli -x script load

And use it with EVALSHA

evalsha 96d1fb35d6173758facda9dbc108296fd4a1512d 1 <myList> <new_element_name> <max_size>


标签: redis