local redis = require "resty.redis"


local function close_redis(red)
    if not red then
        return
    end

    local pool_max_idle_time = 60000
    local pool_size = 10
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx_log(ngx_err, "set redis keepalive error: ", err)
    end
end


local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect(redis_host, redis_port)
if not ok then
    ngx_log(ngx_err, "connect to redis server error: ", err)
    return
end

local count, err = red:get_reused_times()
if count == 0 then
    local ok, err = red:auth(redis_pass)
    if not ok then
        ngx_log(ngx_err, "redis password error: ", err)
        return
    end
elseif err then
    ngx_log(ngx_err, "get redis reused_times error: ", err)
    return
else
    ngx_log(ngx_info, "get_reused_times: ", count)
end

red:mget()
red:mget(unpack({key1, key2}))
red:set()
red:del()
red:smembers()

close_redis(red)

nginx.conf

pcre_jit on;

1)ngx.re.find

from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)
options可选值:i是忽略大小写,o是仅编译一次,m是多行模式,j是启用pcre jit编译。

local from, to, err = ngx.re.find("hello world", [[hello]], "ijo")
if from then
    ngx.say("found")
else
    ngx.say("not found")
end

2)ngx.re.match

只有第一次匹配的结果被返回,如果没有匹配,则返回nil;或者匹配过程中出现错误时,
也会返回nil,此时错误信息会被保存在err中。

当匹配的字符串找到时,一个Lua table captures会被返回,
captures[0]中保存的就是匹配到的字串,
captures[1]保存的是用括号括起来的第一个子模式(捕获分组)的结果,
captures[2]保存的是第二个子模式(捕获分组)的结果,依次类似。

local m, err = ngx.re.match(ngx.var.http_user_agent, [[python-request|python3]], "ijo")
if m then
    ngx.say("match: ", m[0])
else
    if err then
        ngx.say("match error: ", err)
        return
    end
    ngx.say("not matched")
end

3)ngx.re.sub()
用来查找匹配模式的串,并将使用替换串把其替换掉,但并不修改原字符串,而是返回一个修改后的字符串的副本。
函数有目标串,模式串,替换串三个参数。

在nginx.conf中配置

http {
    init_by_lua_file init.lua;
    init_worker_by_lua_file init_worker.lua;
}

init.lua

local process = require "ngx.process"

local ok, err = process.enable_privileged_agent()
if not ok then
    ngx.log(ngx.ERR, "enable privileged agent failed, error: ", err)
end

init_worker.lua

local process = require "ngx.process"

local function timer_work(delay, worker)
    local timer_work

    timer_work = function (premature)
        if not premature then
            local status, msg = pcall( worker )
            if not status then
                ngx_log(ngx_err, "timer work: ", msg)
            end
            ngx_timer_at(delay, timer_work)
        end
    end

    ngx_timer_at(delay, timer_work)
end

local function load_data()

end

if process.type() == "privileged agent" then
    timer_work(delay, load_data)
end

ngx.req.get_method
获取当前请求的 HTTP 请求方法名称。
结果为类似 "GET" 和 "POST" 的字符串,而不是 HTTP 方法常量 中定义的数值。

ngx.req.set_method
用 method_id 参数的值改写当前请求的 HTTP 请求方法。
当前仅支持 HTTP 请求方法 中定义的数值常量,例如 ngx.HTTP_POST 和 ngx.HTTP_GET。

ngx.req.set_uri
ngx.req.set_uri_args
ngx.req.get_uri_args
ngx.req.get_post_args
ngx.req.get_headers
ngx.req.set_header
ngx.req.clear_header
ngx.req.read_body -- 同步读取客户端请求体,不阻塞 Nginx 事件循环。
ngx.req.discard_body -- 明确丢弃请求体,也就是说,读取连接中的数据后立即丢弃。
ngx.req.get_body_data
ngx.exec -- 使用 uri、args 参数执行一个内部跳转
ngx.redirect -- 发出一个 HTTP 301 或 302 重定向到 uri。
ngx.print -- 将输入参数合并发送给 HTTP 客户端 (作为 HTTP 响应体)
ngx.say -- 与 ngx.print 相同,同时末尾添加一个回车符。
ngx.log -- 将参数拼接起来,按照设定的日志级别记入 error.log。
ngx.exit

当 status >= 200 (即 ngx.HTTP_OK 及以上) 时,本函数中断当前请求执行并返回状态值给 nginx。
当 status == 0 (即 ngx.OK) 时,本函数退出当前的“处理阶段句柄” (或当使用 content_by_lua 指令时的“内容句柄”) ,继续执行当前请求的下一个阶段 (如果有)。
status 参数可以是 status argument can be ngx.OK, ngx.ERROR, ngx.HTTP_NOT_FOUND,
ngx.HTTP_MOVED_TEMPORARILY 或其它 HTTP status constants。

ngx.sleep -- 无阻塞地休眠特定秒。时间可以精确到 0.001 秒 (毫秒)。
ngx.escape_uri -- 对 str 进行 URI 编码。
ngx.unescape_uri -- 将转义过的 URI 内容 str 解码。
ngx.encode_args -- 根据 URI 编码规则,将 Lua 表编码成一个查询参数字符串。
ngx.decode_args -- 将 URI 编码的查询字符串解码为 Lua 表。本函数是 ngx.encode_args 的逆函数。
ngx.encode_base64 -- 通过 base64 对 str 字符串编码。
ngx.decode_base64 -- 通过 base64 解码 str 字符串得到未编码过的字符串。如果 str 字符串没有被正常解码将会返回 nil。
ngx.crc32_short -- 通过一个字符串计算循环冗余校验码。
ngx.crc32_long -- 通过一个字符串计算循环冗余校验码。
ngx.hmac_sha1 -- 通过 str 待运算数据和 secret_key 密钥串生成结果。

local key = "thisisverysecretstuff"
local src = "some string we want to sign"
local digest = ngx.hmac_sha1(key, src)
ngx.say(ngx.encode_base64(digest))

ngx.md5 -- 通过 MD5 计算 str 字符串返回十六进制的数据。
ngx.md5_bin -- 通过 MD5 计算 str 字符串返回二进制的数据。
ngx.sha1_bin -- 通过 SHA-1 计算 str 字符串返回二进制的数据。
ngx.quote_sql_str -- 根据 MySQL 转义规则返回一个转义后字符串。
ngx.today -- 从nginx的时间缓存(不像Lua的日期库,该时间不涉及系统调用)返回当前的日期(格式:yyyy-mm-dd)。
ngx.time -- 返回从新纪元到从nginx时间缓存(不像Lua的日期库,该时间不涉及系统调用))获取的当前时间戳所经过的秒数。
ngx.now -- 返回一个浮点型的数字,该数字是从新纪元到从nginx时间缓存(以秒为单位,小数部分是毫秒)。
ngx.localtime -- 返回nginx时间缓存(不像Lua的os.date函数,该时间不涉及系统调用)的当前时间戳(格式:yyyy-mm-dd hh:mm:ss)。
ngx.utctime -- 返回nginx时间缓存(不像Lua的os.date函数,该时间不涉及系统调用)的当前时间戳(格式:yyyy-mm-dd hh:mm:ss)。
ngx.cookie_time -- 返回一个可以用做 cookie 过期时间的格式化字符串。参数 sec 是以秒为单位的时间戳(比如 ngx.time 的返回)。

ngx.say(ngx.cookie_time(1290079655))

ngx.http_time -- 返回一个可以用在 http 头部时间的格式化字符串
ngx.parse_http_time -- 解析 http 时间字符串(比如从 ngx.http_time 返回内容)。成功情况下返回秒数,错误的输入字符格式返回 nil 。
ngx.is_subrequest -- 如果当前请求是 nginx 子请求返回 true ,否则返回 false 。
ngx.re.find -- 与 ngx.re.match 类似但只返回匹配结果子字符串的开始索引
ngx.re.sub -- 匹配字符串 subject,将第一个结果替换为字符串或函数类型参数 replace。
ngx.re.gsub -- 就象 ngx.re.sub, 但执行全局替换。
ngx.shared.DICT -- 获取基于共享内存名为 DICT 的 Lua 字典对象,它是一个共享内存区块

 http {
     lua_shared_dict dogs 10m;
     server {
         location /set {
             content_by_lua '
                 local dogs = ngx.shared.dogs
                 dogs:set("Jim", 8)
                 ngx.say("STORED")
             ';
         }
         location /get {
             content_by_lua '
                 local dogs = ngx.shared.dogs
                 ngx.say(dogs:get("Jim"))
             ';
         }
     }
 }

ngx.shared.DICT.get -- 从 ngx.shared.DICT 字典中获取名为 key 的键 (key) 值。如果此 key 不存在或已过期,返回 nil。

local cats = ngx.shared.cats
local value, flags = cats:get("Marry")

ngx.get_phase

检索当前正在执行的阶段名称。
返回值可能有:init,init_worker,set,rewrite,access,content,header_filter,body_filter,log,timer

ngx.thread.spawn
ngx.timer.at -- 创建一个 Nginx 定时器。

第一个参数 delay,指定这个定时器的延迟时间,秒为单位。
我们可以指定带有小数部分的时间像0.001,这里代表 1 毫秒。
当需要立即执行当前挂起的处理,指定延迟为0即可。
第二个参数callback,可以是任何 Lua 函数,在指定的延迟时间之后,将会在一个后台的“轻线程”中被调用。

HTTP 方法常量
ngx.HTTP_GET
ngx.HTTP_HEAD
ngx.HTTP_PUT
ngx.HTTP_POST
ngx.HTTP_DELETE
ngx.HTTP_OPTIONS (v0.5.0rc24 版本加入)
ngx.HTTP_MKCOL (v0.8.2 版本加入)
ngx.HTTP_COPY (v0.8.2 版本加入)
ngx.HTTP_MOVE (v0.8.2 版本加入)
ngx.HTTP_PROPFIND (v0.8.2 版本加入)
ngx.HTTP_PROPPATCH (v0.8.2 版本加入)
ngx.HTTP_LOCK (v0.8.2 版本加入)
ngx.HTTP_UNLOCK (v0.8.2 版本加入)
ngx.HTTP_PATCH (v0.8.2 版本加入)
ngx.HTTP_TRACE (v0.8.2 版本加入)

HTTP 状态常量
value = ngx.HTTP_OK (200)
value = ngx.HTTP_CREATED (201)
value = ngx.HTTP_SPECIAL_RESPONSE (300)
value = ngx.HTTP_MOVED_PERMANENTLY (301)
value = ngx.HTTP_MOVED_TEMPORARILY (302)
value = ngx.HTTP_SEE_OTHER (303)
value = ngx.HTTP_NOT_MODIFIED (304)
value = ngx.HTTP_BAD_REQUEST (400)
value = ngx.HTTP_UNAUTHORIZED (401)
value = ngx.HTTP_FORBIDDEN (403)
value = ngx.HTTP_NOT_FOUND (404)
value = ngx.HTTP_NOT_ALLOWED (405)
value = ngx.HTTP_GONE (410)
value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)
value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
value = ngx.HTTP_SERVICE_UNAVAILABLE (503)
value = ngx.HTTP_GATEWAY_TIMEOUT (504) (v0.3.1rc38 版本加入)

日志级别常量
ngx.STDERR
ngx.EMERG
ngx.ALERT
ngx.CRIT
ngx.ERR
ngx.WARN
ngx.NOTICE
ngx.INFO
ngx.DEBUG