如何在 Lua 中创建我的 redis 连接单例?

How to make my redis connection Singleton in Lua?

我正在尝试通过 Nginx 和 Lua 处理传入的 HTTP 请求。我需要在每个请求中从 Redis 读取蓝色,目前,我通过以下代码在每个请求中打开一个 Redis 连接:

local redis = require "resty.redis"
local red = redis:new()

local ok, err = red:connect("redis", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local res, err = red:auth("abcd")
if not res then
    ngx.log(ngx.ERR, err)
    return
end 

有什么方法可以使此连接成为静态连接或单例连接以提高我的请求处理程序性能?

It is impossible to share a cosocket object (and, therefore, a redis object, check 了解详情)不同请求之间:

The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it. So never pass the cosocket object to any other Lua handler (including ngx.timer callback functions) and never share the cosocket object between different Nginx requests.

然而,nginx/ngx_lua 在内部使用 a connection pool

Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method

也就是说,您只需要使用 sock:setkeepalive() instead of sock:close() for persistent connections. The redis object interface has a corresponding method: red:set_keepalive()

您仍然需要在每个请求的基础上创建一个 redis 对象,但这将有助于避免连接开销。