function get_from_cache(key) local cache_ngx = ngx.shared.my_cache local value = cache_ngx:get(key) return value end 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 set_to_cache('a',1,1000) ngx.say(get_from_cache('a'))
lru catch:这个cache是worker级别的,不会在nginx wokers之间共享。并且,它是预先分配好key的数量,而shared dcit需要自己用key和value的大小和数量,来估算需要把内存设置为多少。
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 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")
shared.dict 使用的是共享内存,每次操作都是全局锁,如果高并发环境,不同worker之间容易引起竞争。所以单个shared.dict的体积不能过大。lrucache是worker内使用的,由于nginx是单进程方式存在,所以永远不会触发锁,效率上有优势,并且没有shared.dict的体积限制,内存上也更弹性,但不同worker之间数据不同享,同一缓存数据可能被冗余存储。+
你需要考虑的,一个是Lua lru cache提供的API比较少,现在只有get、set和delete,而ngx shared dict还可以add、replace、incr、get_stale(在key过期时也可以返回之前的值)、get_keys(获取所有key,虽然不推荐,但说不定你的业务需要呢);第二个是内存的占用,由于ngx shared dict是workers之间共享的,所以在多worker的情况下,内存占用比较少。