1.OpenResty有两种缓存方式,分别是shared_dict和lua-resty-lrucache
2.shared_dict(字典缓存)方式 第一步:在nginx.conf里面添加配置:
lua_shared_dict my_cache 128m; --mycahe是lua_shared_dict的缓存名字
第二步:在代码里面使用,示例代码:
function get_from_cache(key)
local my_cache = ngx.shared.my_cache
local value = my_cache:get(key)
return value
end
shared_dict是内存缓存,worker之间是共享缓存的,操作的是同一个,所以必须保证操作的原子性。有get\set\delete\add\replace\incr\get_keys\get_stale操作。
3.lua-resty-lrucache(lua实现的<最近经常使用>的缓存)方式 示例代码:
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("dog", 32)
ngx.say("dog: ", c:get("dog"))
lua-resty-lrucache是每个worker占用一个。有get\set\delete操作。
4.测试缓存对服务性能的影响