咱们介绍下在 OpenResty 里面,有哪些缓存的方法。nginx
咱们看下面这段代码:git
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
这里面用的就是 ngx shared dict cache 。你可能会奇怪, ngx.shared.my_cache 是从哪里冒出来的?没错,少贴了 nginx.conf 里面的修改:github
lua_shared_dict my_cache 128 m;
如同它的名字同样,这个 cache 是 nginx 全部 worker 之间共享的,内部使用的 LRU 算法(最近常常使用)来判断缓存是否在内存占满时被清除。算法
直接复制下春哥的示例代码:缓存
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
能够看出来,这个 cache 是 worker 级别的,不会在 nginx wokers 之间共享。而且,它是预先分配好 key 的数量,而 shared dcit 须要本身用 key 和 value 的大小和数量,来估算须要把内存设置为多少。memcached
在性能上,两个并无什么差别,都是在 Nginx 的进程中获取到缓存,这都比从本机的 memcached 或者 Redis 里面获取,要快不少。性能
你须要考虑的,一个是 lua lru cache 提供的 API 比较少,如今只有 get 、 set 和 delete ,而 ngx shared dict 还能够 add 、 replace 、 incr 、 get_stale (在 key 过时时也能够返回以前的值)、 get_keys (获取全部 key ,虽然不推荐,但说不定你的业务须要呢);第二个是内存的占用,因为 ngx shared dict 是 workers 之间共享的,因此在多 worker 的状况下,内存占用比较少。ui