ledgetech / lua-resty-redis-connector

Connection utilities for lua-resty-redis
234 stars 71 forks source link

why my Redis connection closed? #9

Closed tangwz closed 7 years ago

tangwz commented 7 years ago

Hello, I use this lua-resty-redis-connector to connect redis sentinel. But when I subscribe the redis channel and read_reply in a while true loop, I received closed error sometimes. My code: The function redis_conn which return a redis-sentinel connection.

redis_conn = function(self)
    local rc = connector.new()
    rc:set_connect_timeout(1000) -- Sets the cosocket connection timeout, in ms.
    rc:set_read_timeout(5000)

    local red, err = rc:connect {
        sentinels = self.config['sentinels'],
        master_name = self.config['master_name'],
        -- db = self.conffig['db'],
    }

    if not red then
        return nil, err
    end

    local ok, err = red:psubscribe(unpack(self.config['channels']))

    if not ok then
        return nil, err
    end

    return red, nil
end

And the main loop.

while true do

    if wb.fatal then
        red:punsubscribe(pusher.config["channels"])
        ngx.log(ngx.ERR, "websocket has disconnected:  ", err)
        return ngx.exit(444)
    end

    if ngx.worker.exiting() then
        return ngx.exit(444)
    end

    local res, err = red:read_reply()

    if not res then
        if err ~= "timeout" then
            ngx.log(ngx.ERR, "Redis read error: ", err)  -- Sometimes I receive "Redis read error: closed,"
            return ngx.exit(444)
        end
    else
        if g_list[res[3]] then
            local ok, err = pusher.ws_send(wb, "msg", res[4])
            if not ok then
                red:punsubscribe(pusher.config["channels"])
                ngx.log(ngx.ERR, "failed to send text: ", err)
                return ngx.exit(444)
            end
        end
    end
end
pintsized commented 7 years ago

I don't think is anything to do with the connector. I haven't used pub/sub in a while, but IIRC your read_reply() just blocks until a message turns up. So with a read timeout of 5 seconds, a gap of 5 seconds between messages would cause the connection to timeout.

Perhaps 60 seconds or something is more appropriate here?

tangwz commented 7 years ago

@pintsized hello, Thanks.Now I know some problom with redis config and I close this. thank you again.