对于 resty.redis 库的二次封装,便于使用。
--name: redis tools
--ctime: 2023/09/02 16:43
--author: 简书tao
--desc: redis function api
local redis = require "resty.redis"
local _M = {}
function _M.new()
local red = redis:new()
red:set_timeouts(1000, 1000, 1000)
return setmetatable({red = red}, {__index = _M})
end
function _M:conn()
local ok, err = self.red:connect("localhost", 6379)
if not ok then
ngx.log(ngx.ERR, "connect redis error: ", err)
return
end
local ok, err = self.red:auth("redis@password")
if not ok then
ngx.log(ngx.ERR, "auth redis error: ", err)
return
end
return true
end
function _M:get(key)
local res, err = self.red:get(key)
if not res then
ngx.log(ngx.ERR, "get key failed: ", key, " err: ", err)
return
end
if res == ngx.null then
ngx.log(ngx.ERR, "not found: ", key)
return
end
return res
end
function _M:set(key, value, exptime)
local res, err = self.red:set(key, value)
if not res then
ngx.log(ngx.ERR, "set key failed: ", key, " err: ", err)
return
end
if exptime then
local ok, err = self.red:expire(key, exptime)
if not ok then
ngx.log(ngx.ERR, "set key exptime failed: ", key, " err: ", err)
return
end
end
return true
end
function _M:incr(key)
local res, err = self.red:incr(key)
if not res then
ngx.log(ngx.ERR, "incr key failed: ", key, " err: ", err)
return
end
return res
end
function _M:persist(key)
local res, err = self.red:persist(key)
if not res then
ngx.log(ngx.ERR, "persist key failed: ", key, " err: ", err)
return
end
return true
end
function _M:close()
local ok, err = self.red:set_keepalive(10000, 100)
if not ok then
ngx.log(ngx.ERR, "close redis error: ", err)
end
end
return _M
整体思路很简单,就是对resty.redis 功能的二次封装。