Redis Lua 脚本 Return Table 并解析对象

Redis Lua Script Return Table and parse object

我有问题,

local searchkey=@searchkey
local blockKeys = redis.call('keys', searchkey)
local table = {}
for i = 0, #blockKeys, 1 do
    local seats = redis.call('HVALS', blockKeys[i])
    table[i] = seats
end
return table

我想为 .net obj 解析此 table 数据 我使用了 StackExchange.Redis 库和 lua return RedisResult 但 lua table 数据未解析 RedisValue[]

有人有想法吗?

A RedisResult 是未知形状数据的通用包装器。有些运算符允许您以多种方式解释数据,例如:

RedisResult val = ...

// simple
int asInt = (int)val; // a single integer
string asString = (string)val; // a single string

string[] asStrings = (string[])val; // a table of strings
double[] asDoubles = (double[])val; // a table of doubles

// more structured

var asKeys = (RedisKey[])val; // a table of keys
var asValues = (RedisValue[])val; // a table of values
var asMulti = (RedisResult[])val; // a table of general purpose values

所以您可以可能将其转换为您需要的内容。然而:在脚本中使用 KEYS 是个大问题,你真的应该改变它。


解决评论中的问题:

Why I dont use keys , can you explain it to me ? Because I check performance, and keys is better than scan, and for table, hvals return binary object so => key, { {key, obj}, {key, obj}}

引用自redis documentation

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code.

每个 Redis 实例都有一个 single-threaded 核心来处理请求。 KEYS 在小型数据库上看起来 很好 ,但是 使用或不使用过滤器 性能是 O(N),其中 N 是 数据库中的总键数,对于大型系统:它可能是灾难性的 坏 - 意思是:花费 10 秒到 return。通常,预计 Redis 操作最多需要 毫秒 ,而当您的 KEYS 操作运行时:没有其他可以。它完全在那段时间阻塞了服务器。

您注意到 KEYSSCAN 更有效,在某些方面 确实如此。 SCAN 的全部意义在于它允许您将操作作为一系列(可能很长)小批量 - "scan the first 100; now scan the next 100 from there; and the next 100" 进行。这有 很多 的开销和延迟,并且涉及更多 round-trips 到服务器,但优点是它不会阻塞服务器核心的单个大块时间。

但是!通常,更好的 either 方法是使用 set 您希望与数据匹配的事物。假设您有一个大数据库并且您对所有 /foo/{whatever} 数据感兴趣。现在;而不是使用 KEYSSCAN 来查找这些值, 如果您需要 迭代该系列中的所有键,则可以简单地删除所有 keys成一组。因此,当您创建 /foo/abc 时,您还通过 [=24= 将 /foo/abc 放入 set /foo/_keys (或其他;这里没有约定) ].现在:要迭代该系列中的所有键,您只需迭代 set /foo/_keys - much 更合适 API.

var asMulti = (RedisResult[])val;
foreach (var item in asMulti)
{
     var asd = (RedisValue[])item;
}

我的脚本 return table 我认为这是 RedisResult[] 并且在 obj 中 所以设计

"key, { {key, obj}, {key, obj}}"