lua学习-3
发布于: 2016-04-10 11:26分类: lua
Nginx全局内存
使用过如Java的朋友可能知道如Ehcache等这种进程内本地缓存,Nginx是一个Master进程多个Worker进程的工作方式,因此我们可能需要在多个Worker进程中共享数据,那么此时就可以使用ngx.shared.DICT来实现全局内存共享。更多API请参考http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT。
1、首先在nginx.conf的http部分分配内存大小
http { include mime.types; default_type application/octet-stream; lua_package_path "lualib/?.lua;;"; #lua 模块 lua_package_cpath "lualib/?.so;;"; #c模块 lua_shared_dict shared_data 1m; lua_code_cache off; ...........................................【省略】
location /test6{ default_type "text/html"; content_by_lua_file html/test6.lua; }
代码test6.lua
--1、获取全局共享内存变量 local shared_data = ngx.shared.shared_data --2、获取字典值 local i = shared_data:get("i") if not i then i = 1 --3、惰性赋值 shared_data:set("i", i) ngx.say("lazy set i ", i, "<br/>") end --递增 i = shared_data:incr("i", 1) ngx.say("i=", i, "<br/>")
访问的时候 第一次是输出
lazy set i 1 i=2
第二次访问输出
i=3
每次刷新都加1
这个功能,做ip的访问次数限制 应该挺好,不用借助redis了。