我希望使用单个调用中的键列表从Redis获取所有集合。根据文档,Redis为此提供了SSCAN命令,但由于我使用StackExchange.Redis作为Redis适配器,我想这个命令在这个适配器中没有任何这样的方法。所以我正在寻找两件事:
由于
答案 0 :(得分:2)
通过传递Set键列表
,在一次调用中获取多个集合
我不清楚这里的具体要求,所以可能有几种方法可以做到这一点。最简单的方法是调用SUNION
,它将重复删除并返回没有订单的结果。
另一种选择是使用Lua脚本,例如:
local reply = {}
for i = 1,#KEYS do
local elems = redis.call('SMEMBERS', KEYS[i])
table.insert(reply, elems)
end
return reply
redis-cli示例(抱歉,.NET不是我的强项):
$ redis-cli SADD s1 foo bar
(integer) 2
$ redis-cli SADD s2 baz qaz
(integer) 2
$ redis-cli --eval script.lua s1 s2
1) 1) "foo"
2) "bar"
2) 1) "baz"
2) "qaz"
注意:如果你的套装有很多成员,那么不管采用什么方法,所有这些成员都会花费很多,并且会很费力。 - 重新考虑对此的需求。
答案 1 :(得分:0)
在单个调用中获取多个SET的示例C#代码如下: 我使用StackExchange.Redis作为Redis连接器:
using StackExchange.Redis;
using System;
using System.Text;
namespace RedisGetMultipleKeys
{
/// <summary>
/// Class to perofrme operations on SE.Redis
/// </summary>
class Program
{
/// <summary>
/// Executes necessary pre-requisites
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Connect Redis
var _cache = Program.Connect();
//Store 10k Sets
string prefix = "user";
StringBuilder keys = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
keys.Append(" " + prefix + i);
_cache.SetAdd(prefix + i, i);
}
var keyList = new RedisKey[10000];
//Generate keys array
for (int i = 0; i < 10000; i++)
{
var key = new RedisKey();
key = prefix + i;
keyList.SetValue(key, i);
}
var startTime = DateTime.Now;
//Perform SUNION
var values = _cache.SetCombine(SetOperation.Union, keyList);
var endTime = DateTime.Now;
TimeSpan diff = endTime.Subtract(startTime);
Console.WriteLine("total time taken to read 10k keys = " + diff);
Console.Read();
//TODO: to be changed accordingly to read Set values returned other than String
foreach (var value in values)
{
Console.WriteLine(value.ToString());
}
endTime = DateTime.Now;
diff = endTime.Subtract(startTime);
Console.WriteLine("total time taken to read 10k keys = " + diff);
Console.Read();
}
/// <summary>
/// Connects to Redis db
/// </summary>
/// <returns>Returns an instance of Redis db</returns>
private static IDatabase Connect()
{
string redisConnection = "localhost:6379,ssl=false,allowAdmin=true,ConnectRetry=3,ConnectTimeout=5000,defaultDatabase=1";
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnection);
return connection.GetDatabase();
}
}
}
我希望它能帮助C#开发人员寻找解决方案。感谢SE.Redis开发团队的Mgravell帮助我提出他的建议。可以在GitHub How to get multiple sets by passing set key list in a single call
找到更多讨论