如果集合中有那么多(计数)元素,如何将 spop 命令与计数一起使用 [英] how to use spop command with count if set have that much (count) element in set

查看:67
本文介绍了如果集合中有那么多(计数)元素,如何将 spop 命令与计数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想从集合中弹出 3 个元素,我如何确保只有在集合中存在 3 个元素时才弹出,否则返回任何错误或其他 msg

Let suppose I want to pop 3 elements from the set, how I ensure that only pop if 3 elements present in a set otherwise return any error or other msg

如何使用带有count"参数的spop"命令.

How to use "spop" command with "count" argument.

推荐答案

你想要的是调用SCARD myKey来测试成员数量,并根据结果调用SPOP.

What you want is to call SCARD myKey to test the number of members, and based on the result call SPOP.

SPOPCOUNT 将返回最多 COUNT 个成员,这意味着如果您的集合只有一两个,它们将被 SPOP 和返回.

SPOP with COUNT will return up to COUNT members, meaning if your set only has one or two, they'll be SPOPed and returned.

您可能希望通过一个原子操作来做到这一点.所以你必须使用 Lua Scrips:

You probably want to do this with one atomic operation. So you have to use Lua Scrips:

EVAL "if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[1]) then return redis.call('SPOP', KEYS[1], ARGV[1]) else return redis.error_reply(KEYS[1]..' does NOT have at least '..ARGV[1]..' members') end" 1 myKey myNumber

让我们看一下脚本:

if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[1]) then 
    return redis.call('SPOP', KEYS[1], ARGV[1]) 
else 
    return redis.error_reply(KEYS[1]..' does NOT have at least '..ARGV[1]..' members')
end

KEYS[1] 指的是键参数,即您感兴趣的集合.通过参数传递键对于您的脚本在 Redis 集群中得到支持非常重要.

KEYS[1] refers to the key parameter, the set you're interested in. It is important to pass keys through parameters for your script to be supported in a Redis Cluster.

ARGV[1] 是传递所需成员数量的附加参数,在您的问题中,它是 3.

ARGV[1] is an additional argument to pass your number of desired members, in your question, it is 3.

该脚本在 Redis 中以原子方式在服务器端运行,并且它只编译一次,因为 Redis 在内部对其进行了缓存.

The script is run atomically server-side within Redis, and it is compiled only once as Redis caches it internally.

您可以使用 SCRIPT LOAD 加载脚本,然后与 EVALSHA 重用,以提高网络性能.

You can use SCRIPT LOAD to load the script and then reuse it with EVALSHA, to also improve networking performance.

这篇关于如果集合中有那么多(计数)元素,如何将 spop 命令与计数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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