Lua脚本从Redis HGETALL调用返回高效字典 [英] Lua script to return efficient dictionary from Redis HGETALL call

查看:143
本文介绍了Lua脚本从Redis HGETALL调用返回高效字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 Lua 脚本中使用 Redis HMGET 并在以下代码中提取特定值.但是 redis.call('HMGET', table_key, hkey1, hkey2, ...) 返回一个平面数组 {hkey1, val1, hkey2, val2, ...}

I need to use Redis HMGET from a Lua script and extract specific values in following code. But redis.call('HMGET', table_key, hkey1, hkey2, ...) return a flat array of {hkey1, val1, hkey2, val2, ...}

通过我写的键提取值:

local function flat_map_get(flat_map, hash_key)
    local i = 1
    while flat_map[i] do
        if flat_map[i] == hash_key then
            return flat_map[i+1]
        end
        i = i+2
    end
end

当然,随着使用量的增长,多次调用此函数会导致性能大幅下降.

Of course, as usage grow, multiple calls to this function presented major performance drop.

HMGET 返回的平面数组中读取值的有效方法是什么?或者以其他方式将返回值转换为正确的键值表?

What is an efficient way to read values from the flat array returned by HMGET? Or otherwise, to convert the returned value into a proper key-value table?

推荐答案

经过一些分析和测试,我们发现以下函数具有良好的性能,并使用它来获得合适的表.

After some profiling and tests, we found the following function to have good performance and use it to get a proper table.

这样就无需为每个哈希键检索调用 getter 函数.

This save the need to call a getter function for each hash key retrieval.

local function hgetall(hash_key)
    local flat_map = redis.call('HGETALL', hash_key)
    local result = {}
    for i = 1, #flat_map, 2 do
        result[flat_map[i]] = flat_map[i + 1]
    end
    return result
end

这篇关于Lua脚本从Redis HGETALL调用返回高效字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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