简体   繁体   English

如何在 Lua 中使我的 redis 连接 Singleton?

[英]How to make my redis connection Singleton in Lua?

I am trying to handle incoming HTTP requests by Nginx and Lua.我正在尝试处理 Nginx 和 Lua 传入的 HTTP 请求。 I need to read a blue from Redis in each request and currently, I open a Redis connection in every request by this code:我需要在每个请求中从 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 

Is there any way to make this connection static or singleton to increase my request handler performance?有什么方法可以建立此连接 static 或 singleton 以提高我的请求处理程序性能?

It is impossible to share a cosocket object (and, therefore, a redis object, check this answer for details) between different requests: 不可能在不同的请求之间共享一个 cosocket object(因此,一个 redis object,请查看此答案以获取详细信息):

The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it.由这个 API function 创建的 cosocket object 与创建它的 Z0AE9478A1DB9D1E2C48EFA 处理程序具有完全相同的生命周期。 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. 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.

However, nginx/ngx_lua uses a connection pool internally:但是,nginx/ngx_lua 内部使用了一个连接池

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在实际解析主机名并连接到远程后端之前,此方法将始终在连接池中查找由先前调用此方法创建的匹配空闲连接

That being said, you just need to use sock:setkeepalive() instead of sock:close() for persistent connections.话虽如此,您只需要使用sock:setkeepalive()而不是sock:close()来实现持久连接。 The redis object interface has a corresponding method: red:set_keepalive() . redis object接口有对应的方法: red:set_keepalive()

You'll still need to create a redis object on a per request basis, but this will help to avoid a connection overhead.您仍然需要根据每个请求创建 redis object,但这将有助于避免连接开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM