Redis - 是否有 blpush [英] Redis - is there a blpush
问题描述
对于跨进程的数据通信,我打算使用Redis列表.生产者推送到列表,而一组消费者使用 BRPOP 消费列表内容.
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.
为了限制列表的大小无限增长,我想将列表大小限制为一个固定值(比如 10K 项).我很惊讶地发现没有像 BLPUSH 或 BRPUSH 这样的等效命令.这是Redis人故意省略的吗?
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?
所以,我假设我必须创建一个带有 Watch/multi 的 Txn 以在推送之前检查列表大小.这是正确的方法,还是有更好的技术可用?
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?
推荐答案
我会为此功能寻找 lua 脚本.
I would go for a lua script for this functionality.
LUA 接受一个键(列表名称)和两个参数,new_element_name
和 max_size
.当列表已满时,返回值可以是 LPUSH
返回值或 -1
.
这是执行此操作的脚本:
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
您应该使用 SCRIPT LOAD 加载一次:
You should load it once with SCRIPT LOAD:
cat blpush.lua | redis-cli -x script load
并与 EVALSHA 一起使用
And use it with EVALSHA
evalsha 96d1fb35d6173758facda9dbc108296fd4a1512d 1 <myList> <new_element_name> <max_size>
这篇关于Redis - 是否有 blpush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!