Skip to content

nginx 全局内存缓存

nginx
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    lua_code_cache off;
    # 缓存空间为 1M,能被所有进程访问并保证原子性。
    lua_shared_dict shared_data 1m;

    server {
        listen       3000;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /lua {
            default_type text/html;
            content_by_lua_file conf/lua/hello.lua;
        }
    }
}
lua
local shared_data = ngx.shared.shared_data  
local i = shared_data:get("i")  

if not i then  
    i = 1  
    shared_data:set("i", i)  
    ngx.say("lazy set i ", i, "<br/>")  
end  
 
i = shared_data:incr("i", 1)  
ngx.say("i=", i, "<br/>")

lua-resty-lrucache

Lua 实现的一个简单的 LRU 缓存,适合在 Lua 空间里直接缓存较为复杂的 Lua 数据结构:它相 比 ngx_lua 共享内存字典可以省去较昂贵的序列化操作,相比 memcached 这样的外部服务又能 省去较昂贵的 socket 操作

https://github.com/openresty/lua-resty-lrucache

nginx
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    # 缓存一定不能关闭,否则每次都会把 cache.lua 重新执行一遍,根本起不到缓存的作用。
    lua_code_cache on;

    server {
        listen       3000;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        # 会去多个地方找,其中一个地方是 lualib。
        # 因此可以在 lualib 下新建 my 目录,再新建 cache.lua 文件。
        location /lua {
            default_type text/html;
            content_by_lua_block {
                require("my/cache").go()
            }        
        }
    }
}

cache.lua

lua
-- file myapp.lua: example "myapp" module

local _M = {}

-- alternatively: local lrucache = require "resty.lrucache.pureffi"
local lrucache = require "resty.lrucache"

-- we need to initialize the cache on the lua module level so that
-- it can be shared by all the requests served by each nginx worker process:
local c, err = lrucache.new(200)  -- allow up to 200 items in the cache
if not c then
    error("failed to create the cache: " .. (err or "unknown"))
end

function _M.go()
    c:set("dog", 32)
    c:set("cat", 56)
    ngx.say("dog: ", c:get("dog"))
    ngx.say("cat: ", c:get("cat"))

    c:set("dog", { age = 10 }, 0.1)  -- expire in 0.1 sec
    c:delete("dog")

    c:flush_all()  -- flush all the cached data
end

return _M