Skip to content

Instantly share code, notes, and snippets.

@tinoji
Last active August 3, 2019 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tinoji/329de20af3c24db11319e1806d345501 to your computer and use it in GitHub Desktop.
Save tinoji/329de20af3c24db11319e1806d345501 to your computer and use it in GitHub Desktop.
Use array in OpenResty shared memory dictionary
local _M = {}
local function split(str, separator)
local result = {}
local pattern = '[^' .. separator .. ']+'
for tmp in string.gmatch(str, pattern) do
table.insert(result, tmp)
end
return result
end
local function trimBracket(str)
return (str:gsub("^{(.*)}$", "%1"))
end
-- serialize
function _M.arrayToString(array)
if #array == 0 then
return '{}'
end
return '{"' .. table.concat(array, '","') .. '"}'
end
local function removeQuatation(str)
local s = str:gsub('"', '')
return s:gsub("'", '')
end
-- deserialize
function _M.stringToArray(str)
local s = trimBracket(str)
s = removeQuatation(s)
return split(s, ',')
end
return _M
@tinoji
Copy link
Author

tinoji commented Aug 3, 2019

sample nginx.conf:

worker_processes 12;

events {
    worker_connections 2048;
}


http {
    lua_shared_dict foo 10m;

    server {
        listen 80;

        location /test {
            content_by_lua_block {
                local function split(str, separator)
                    local result = {}
                    local pattern = '[^' .. separator .. ']+'

                    for tmp in string.gmatch(str, pattern) do
                        table.insert(result, tmp)
                    end

                    return result
                end

                local function trimBracket(str)
                    return (str:gsub("^{(.*)}$", "%1"))
                end

                local function arrayToString(array)
                    if #array == 0 then
                        return '{}'
                    end

                    return '{"' .. table.concat(array, '","') .. '"}'
                end

                local function removeQuatation(str)
                    local s = str:gsub('"', '')
                    return s:gsub("'", '')
                end

                local function stringToArray(str)
                    local s = trimBracket(str)
                    s = removeQuatation(s)
                    return split(s, ',')
                end

                local intbl = {"abc", "def"}
                -- add to shared
                ngx.shared.foo:add("key", arrayToString(intbl))
                ngx.say("stored")

                -- get from shared
                local outtbl = stringToArray(ngx.shared.foo:get("key"))
                ngx.say(table.concat(outtbl, ":"))
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment