openrestry 缓存
2018-08-31 17:26
197 查看
OpenResty 的缓存
我们介绍下在 OpenResty 里面,有哪些缓存的方法。使用 lua shared dict
我们看下面这段代码: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 里面的修改:
lua_shared_dict my_cache 128 m;
如同它的名字一样,这个 cache 是 nginx 所有 worker 之间共享的,内部使用的 LRU 算法(最近经常使用)来判断缓存是否在内存占满时被清除。
使用 lua LRU cache
直接复制下春哥的示例代码: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 的大小和数量,来估算需要把内存设置为多少。
如何选择?
在性能上,两个并没有什么差异,都是在 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 的情况下,内存占用比较少。
相关文章推荐
- iOS工作记录10:清理缓存
- ASP.NET MVC4系列页面缓存、缓存依赖SQL(真实项目注意细节)
- WKWebView简单使用及关于缓存的问题
- http协议学习-缓存的实现原理
- listView中多个listItem布局时,convertView缓存及使用
- 一个不错的PHP缓存类介绍和PHP缓存函数介绍以及使用
- EasyJWeb+JPA(Hibernate3.2)+Spring2构架缓存技术
- 面对处理器缓存,一些旧有的性能优化技巧已然失效
- 图片缓存之内存缓存技术LruCache,软引用
- [MySQL性能优化系列]提高缓存命中率
- 缓存、缓存算法和缓存框架简介
- java缓存技术memcached实例
- 现代3D图形编程学习--opengl使用不同的缓存对象(译者添加)
- ABP框架 - 缓存( 转)
- HTML5 离线存储实战之manifest(附缓存整个文件夹的方法)
- C# ActiveX 中static变量缓存的问题
- Hibernate的二级缓存
- 关于解决Windows 7重建图标缓存图标显示错误
- 使用LruCache缓存,轻松解决图片过多造成的OOM
- 火狐浏览器怎么清理缓存、cookie等?