OpenResty 缓存 Cache
说明
缓存:
- 内存 > SSD > 机械磁盘
- 本机 > 网络
- 进程内 > 进程间
原则
- 越靠近用户的请求越好
- 尽量使用本进程和本机的缓存解决
shared_dict
- Lua shared dict 在 Nginx 所有 worker 之间是共享的,内部使用的
LRU 算法(最近最少使用)
淘汰数据nginx.conf
中配置 lua_shared_dict my_cache 128m;
- 通过共享内存实现不同 Worker 进程之间的数据共享
- 每次操作都是全局锁,高并发环境下不同 worker 之间易产生竞争
ngx.shared_dict
API:add/replace/incr/get_keys/get_stale
http {
...
lua_shared_dict test_cache 128m;
...
server {
listen 80;
location /hello-world {
default_type text/html;
content_by_lua_block {
function get_from_cache(key)
local my_cache = ngx.shared.test_cache
local value = my_cache::get(key)
return value
end
function set_to_cache(key, value, exptime)
local my_cache = ngx.shared.test_cache
local success, err, forcible = my_cache::set(key, value, exptime)
return success
end
set_to_cache("abc", 123)
ngx.say(get_from_cache("abc"))
}
}
}
}
lua-resty-lrucache
local lrucache = require "resty.lrucache"
local c = lrucache.new(200) -- allow up to 200 items in the cache
if not c then
return error("failed to create the cache: " .. (err or "unknown"))
end
c:set("abc", 12)
ngx.say("abc: ", c:get("abc"))
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 = lrucache.new(200) -- allow up to 200 items in the cache
if not c then
return 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")
end
return _M
lua_code_cache
默认为缓存启用 lua_code_cache on;
其他
- 缓存失效风暴,可通过
lua-resty-lock
加锁规避