之前在openresty上面做过一些账号和网络权限控制,账号和网段的数据通过调用http接口获取;但是有两个方面考量需要将数据存入redis中。一是http接口有可能发生故障,不能完全依赖接口获取数据;二是可能有少量的需求要手动设置账号数据,比如临时新增或者移除需要控制的账号。
openresty官方提供了redis模块,但是如果自己去调用官方提供的api的话,需要将基本的api封装成一个方法,以此来减少冗余的代码。好在已经有开源项目帮我们做了这些,本文主要是参考网友的开源贡献:GitHub - anjia0532/lua-resty-redis-util: openresty/lua-resty-redis 封装工具类
安装方法:
将redis-util.lua文件放到/xx/lualib/resty/目录下即可
使用方式:
local redis = require("resty.redis-util")
--创建redis实例方法
local function new_redis(ip, port_num, pwd)
local red = redis:new({
host=ip,
port=port_num,
db_index=0,
password=pwd,
timeout=3000, --超时时间
keepalive=60000, --连接保持时间
pool_size=100 --连接池大小
});
return red
end
-- 创建实例
local red = new_redis("10.1.1.1", 6379, "xxxxxxxx")
local func = red:subscribe("channel")
if not func then
return nil
end
--死循环处理监听到的消息
while true do
local res, err = func()
--3000ms超时,如果不是超时错误就关闭订阅
if err and err ~= "timeout" then
func(false)
end
--收到订阅消息后的逻辑处理
if res then
red:sadd("channel", ngx.md5(ngx.now()))
end
end
常见问题:
2022/12/12 15:55:42 [error] 9#0: *9 lua tcp socket read timed out,
client: 10.1.1.1, server: abc.def.com.cn,
request: "GET /testHttp HTTP/1.0", host: "abc.def.com.cn"
根据lua_socket_log_errors的描述来看,应该在 Lua 中处理 socket 错误,
并在http,server,location等范围中配置下面语句来关闭错误日志:
lua_socket_log_errors off;