openresty: nginx worker不同请求之间共享数据

To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua require builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.

要在同一个nginx worker进程处理的不同请求间共享数据,可以利用lua的特性,把共享数据封装到lua模块中,然后使用require导入模块。因为require lua模块只会加载一次模块,然后所有的协程共享模块的同一个副本(包括代码和数据)。需要注意的是,lua的全局变量并不会在不同请求之间存在,这是因为每个请求每个协程,相互是隔离的。

openresty提供了lua lru cache作为worker级别的缓存,可以缓存固定数量的key-value,并且由于只能在worker内共享,不会触发锁,效率上有优势。lua lru cache提供的api只有get、set、delete。在具体开发时,可以封装一个module用于操作共享数据,实现不同请求之间数据共享。

local _M = {}

local lrucache = require "resty.lrucache"

local c, err = lrucache.new(200)
if not c then
    return error("failed to create the cache: " .. (err or "unknown"))
end

function _M.set(key, value, exptime)
    if not exptime then
        exptime = 0
    end
    c:set(key, value, exptime)
end

function _M.get(key)
    return c:get(key)
end

function _M.delete(key)
    c:delete(key)
end

return _M

如果要实现nginx级别、跨worker共享数据,可以用ngx.shared.dict,或者外部的数据服务,例如memcached、redis。如果数据量不大,并且业务允许,推荐用ngx.shared.dict,效率高。

nginx.conf中配置lua_shared_dict my_cache 128m;,http请求或tcp请求都可以用。

local function get_from_cache(key)
    local cache_ngx = ngx.shared.my_cache
    local value = cache_ngx:get(key)
    return value
end
local function set_to_cache(key, value, exptime)
    if not exptime then
        exptime = 0
    end
    local cache_ngx = ngx.shared.my_cache
    local succ, err, forcible = cache_ngx:set(key, value, exptime)
    return succ
end
posted @ 2017-05-10 18:48  我的娃会叫爸爸啦  阅读(1725)  评论(0编辑  收藏  举报