Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@tinoji 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
You can’t perform that action at this time.