问题如标题所示
使用lua脚本连接docker中的redis时出现了成功连接和失败连接交替出现的问题。
其中使用的虚拟机版本为CentOS7,Docker中的redis版本为6.2.6,虚拟机中的redis版本为7.2.4
在产生失败的连接时错误日志中显示的信息为
2024/02/19 00:38:55 [error] 5817#5817: *99 lua entry thread aborted: runtime error: /usr/local/openresty/lualib/resty/redis.lua:166: bad request
stack traceback:
coroutine 0:
[C]: in function 'connect'
/usr/local/openresty/lualib/resty/redis.lua:166: in function 'connect'
/usr/local/openresty/lualib/common.lua:20: in function 'read_redis'
/usr/local/openresty/nginx/lua/item.lua:8: in function 'get_data'
/usr/local/openresty/nginx/lua/item.lua:24: in main chunk, client: 192.168.152.12, server: localhost, request: "GET /api/item/10002 HTTP/1.1", host: "192.168.152.11:8081"
发生错误的代码片段,代码拷贝自教程视频的资料,并略作修改
-- 导入redis
local redis = require('resty.redis')
-- 初始化redis
local red = redis:new()
red:set_timeouts(1000, 1000, 1000)
-- 关闭redis连接的工具方法,其实是放入连接池
local function close_redis(red)
local pool_max_idle_time = 10000 -- 连接的空闲时间,单位是毫秒
local pool_size = 100 --连接池大小
local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
if not ok then
ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
end
end
-- 查询redis的方法 ip和port是redis地址,key是查询的key
local function read_redis(key)
-- 获取一个连接
local ok, err = red:connect('127.0.0.1', '6380')
if not ok then
ngx.log(ngx.ERR, "连接redis失败 : ", err)
return nil
end
-- 查询redis
local resp, err = red:get(key)
-- 查询失败处理
if not resp then
ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
end
--得到的数据为空处理
if resp == ngx.null then
resp = nil
ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
end
close_redis(red)
return resp
end
-- 封装函数,发送http请求,并解析响应
local function read_http(path, params)
local resp = ngx.location.capture(path,{
method = ngx.HTTP_GET,
args = params,
})
if not resp then
-- 记录错误信息,返回404
ngx.log(ngx.ERR, "http查询失败, path: ", path , ", args: ", args)
ngx.exit(404)
end
return resp.body
end
-- 将方法导出
local _M = {
read_http = read_http,
read_redis = read_redis
}
return _M
测试结果
- 使用redis-cli或者其他redis客户端都能远程或者本地正常稳定连接docker中的redis容器,而使用resty-redis则无法稳定连接。
- resty-redis连接非docker容器中的redis(版本为7.2.4)则表现为正常
原因不明,网上没有找到相关资料,猜测可能是版本问题