HGETALL调用返回有效的字典

HGETALL调用返回有效的字典

本文介绍了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, ...}

要通过我写的键提取值:

To extract values by key I wrote:

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调用返回有效的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:14