从 Redis 集合或列表中取出多个项目的有效方法是什么,保证收到的数量 [英] What’s an efficient way to take multiple items out of a Redis set or list, guaranteeing the number received

查看:79
本文介绍了从 Redis 集合或列表中取出多个项目的有效方法是什么,保证收到的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表(如果这是唯一的方法,它可以是一个集合).我连接了多个客户端,该列表将一次从外部填充一个.

I have list (it can be a set if that’s the only way). I have a number of clients connected, the list will be being filled up externally one at a time.

我需要一种有效的方法将 N 项从该列表中批量取出到一个客户端中.我不在乎它最终在哪个客户端上,只要推送到列表中的前 N 个项目最终有一个客户端,而下一个 N 可能最终在另一个(或相同).

I need an efficient way to take N items out of that list, as a batch, into one client. I don’t care which client it ends up on, just that the first N items pushed into the list end up with one client, and the next N may end up on another (or the same).

我真的不知道如何用列表来实现这一点,我可以阻止流行,但一次只能阻止一个.我真的更喜欢从列表中排序.

I’m really not sure how I could achieved this with lists, I can block for pop but only one at a time. I’d really prefer the ordering from lists.

我想我可以使用集合,让所有客户端都使用 SCARD 访问 Redis.当他们检测到计数为 => 时,SPOP for N.这应该让我至少有一个客户端填充 N,并且每个接收少于 N 的客户端将它们返回到集合中.

I was thinking I could use sets, have all clients hitting Redis with SCARD. When they detect the count is =>, SPOP for N. That should get me at least one client filled with N, and every client that receives fewer than N returns them back to the set.

我重复 SCARD 的事实感觉真的很糟糕,并且不可靠地将事情传回去.

The fact I’m repeating the SCARD feels really bad, and passing things back in unreliable.

有没有更多的东西可以支持这种流程,或者更清晰的算法(理想情况下有一个列表?)

Is there anything more baked in to support this sort of flow, or a cleaner algorithm (that ideally has a list?)

推荐答案

你可以将逻辑包装成一个 Lua 脚本,以确保客户端获得 N 个连续项.

You can wrap the logic into a Lua script, to make sure the client gets N sequential items.

local key = KEYS[1]
local N = tonumber(ARGV[1])

local size = redis.call("llen", key)

if size < N then return {} end    -- ensure that there're at least N items

local res = {}
for i = 1, N do                   -- get N items in a transaction
    res[i] = redis.call("lpop", key);
end

return res

这篇关于从 Redis 集合或列表中取出多个项目的有效方法是什么,保证收到的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆