Redis 使用 Lua 實現 split 結合 HMGET 批量讀取數據

一個簡單的例子,Redis 使用 Lua 實現 split 方法分割字符串爲數組,並通過 HMGET 批量讀取數據。

用例說明:
哈希隊列 H_TEST 的鍵 ids 中,存儲着所需要批量讀取的元素鍵名的字符串,
首先需要將讀取到的字符串按 “,” 逗號分割成數組,再通過 hmget 方法來獲取所有元素並返回。

對 Lua 不熟悉,還是小白一隻,只是湊合着功能夠用,沒有太多專研。
split 方法的實現是網上大神寫的,這裏借來用用

<?php
        $key = 'H_TEST';
        // 字符串分割轉換爲數組的函數
        $script = <<<EOF
function string:split(sep)
    local sep, fields = sep or ",", {};
    local pattern = string.format("([^%s]+)", sep);
    self:gsub(pattern, function(c) fields[#fields+1] = c end);
    return fields;
end;
EOF;
        // 用於批量讀取的哈希隊列中的鍵名
        // 隊列中並不存在鍵名爲 8 的元素,此處只是作爲查找不到元素時的演示
        $script .= 'redis.call("hset", KEYS[1], "ids", "1,8,2,3");';
        // 設置測試數據
        $script .= 'redis.call("hset", KEYS[1], "1", "a");';
        $script .= 'redis.call("hset", KEYS[1], "2", "b");';
        $script .= 'redis.call("hset", KEYS[1], "3", "c");';
        $script .= 'redis.call("hset", KEYS[1], "4", "d");';
        // 獲得需要批量讀取的鍵名
        $script .= 'local idStr = redis.call("hget", KEYS[1], "ids");';
        $script .= 'if (idStr and idStr ~= "") then';
        $script .= '    local idArr = idStr:split();';
        $script .= '    local vals = redis.call("hmget", KEYS[1], unpack(idArr));';
        $script .= '    return {idArr,vals};';
        $script .= 'else';
        $script .= '    return nil;';
        $script .= 'end;';
        $res = $this->redis->eval($script, [$key], 1);
        var_dump($res);

輸出結果:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章