nrk / redis-lua

A Lua client library for the redis key value storage system.
MIT License
731 stars 239 forks source link

how to maintain a long-time connection with Redis #23

Closed coanor closed 10 years ago

coanor commented 11 years ago

I have implemented the Redis pool. But sometimes (maybe 1 hour) the connection within the pool will fail to execute commands(Redis is running, not down), I think the connection is closed(may be by server or client), is there any way to maintain a longtime(maybe forever) connection?

nrk commented 11 years ago

You could try by using the timeout option set to -1:

redis.connect({ host = '127.0.0.1', timeout = -1 })

Internally redis-lua uses settimeout of the underlying LuaSocket instance.

Slightly related, since redis.connect also accepts raw socket instances to initialize the redis client, maybe you could even manage / keep only the socket instances in your pool and create client instances like in the following snippet to gain even more control over the socket setup:

redis.connect(rawsocket)
rafis commented 10 years ago

If I set timeout to something like 300 and check connection using ping(), but ping() can return not just true/false, but error() too. Is it proper to check like this:

-- check connection to redis-server and reconnect if connection lost
local ok, err = pcall(function() return client_redis:ping() end)
if ok then
    ok = err
end
if not ok then
    -- reconnect to redis-server
    client_redis = redis.connect('127.0.0.1', '6379')
end