Openresty 入门

  • hello world
server {
   listen 80;
   server_name _;

   location / {
      default_type text/html;
      content_by_lua '
         local ip = ngx.var.remote_addr
         ngx.say("<p>welcome:</p>",ip)

        ';
   }
}
  • 本地共享内存区域读写
# 在http主模块中使用lua_shared_dict 创建一个内存共享区域,可以被各个worker读取
lua_shared_dict item_cache 150m;

server {
   listen 80;
   server_name _;

   location / {
      default_type text/html;
      content_by_lua '
         local ip = ngx.var.remote_addr
         ngx.say("<p>welcome:</p>",ip)

        ';
   }

  location ~ /add/ {
      default_type text/html;
      content_by_lua_file /usr/local/openresty/dolua/cache.lua;
  }

  location ~ /get/ {
      default_type text/html;
      content_by_lua '
        local local_cache = ngx.shared.item_cache
        local one = local_cache:get("date")
        local two = local_cache:get("ip")
        if not one then
           ngx.say(ngx.now() .. ",not found")
        else
           ngx.say("A:",one,"<br>","B:",two)
        end
        ';
  }
}
# 外部lua脚本cache.lua内容如下:
-- nginx共享缓存读写
local local_cache = ngx.shared.item_cache
-- 写入数据key,value,expire()
local_cache:set("date",os.date("%a, %d %b %Y %X GMT"),50)

local_cache:set("ip",ngx.var.remote_addr,90)

ngx.say("add cache down!")