Node JS Redis客户端连接重试

4

目前我正在使用https://github.com/mranney/node_redis作为我的Node Redis客户端。

client.retry_delay默认设置为250毫秒。

我尝试连接到Redis,一旦连接成功,我手动停止了Redis服务器,以查看client.retry_delay是否起作用。但我没有看到它起作用。

以下日志消息记录在使用createClient创建的redisClients的readyend事件上:

[2012-03-30 15:13:05.498] [INFO] Development - Node Application is running on port 8090
[2012-03-30 15:13:08.507] [INFO] Development - Connection Successfully Established to  '127.0.0.1' '6379'
[2012-03-30 15:16:33.886] [FATAL] Development - Connection Terminated to  '127.0.0.1' '6379'

当服务器重新启动后,我没有看到“成功”消息[未触发就绪事件]。

我错过了什么吗?重试常数将在何时使用?是否有一种方法可以找出从节点失败后redis服务器何时重新上线?

3个回答

11

我无法重现这个问题。你能否尝试运行以下代码,停止Redis服务器并检查日志输出?

var client = require('redis').createClient();

client.on('connect'     , log('connect'));
client.on('ready'       , log('ready'));
client.on('reconnecting', log('reconnecting'));
client.on('error'       , log('error'));
client.on('end'         , log('end'));

function log(type) {
    return function() {
        console.log(type, arguments);
    }
}

我找到了问题,之前我没有处理错误事件。现在它像魔法般工作了。感谢你的代码 :) - Tamil

2

2020年2月的回答:

const redis = require('redis');
const log = (type, fn) => fn ? () => {
    console.log(`connection ${type}`);
} : console.log(`connection ${type}`);

// Option 1: One connection is enough per application
const client = redis.createClient('6379', "localhost", {
    retry_strategy: (options) => {
        const {error, total_retry_time, attempt} = options;
        if (error && error.code === "ECONNREFUSED") {
            log(error.code); // take actions or throw exception
        }
        if (total_retry_time > 1000 * 15) { //in ms i.e. 15 sec
            log('Retry time exhausted'); // take actions or throw exception
        }
        if (options.attempt > 10) {
            log('10 attempts done'); // take actions or throw exception
        }
        console.log("Attempting connection");
        // reconnect after
        return Math.min(options.attempt * 100, 3000); //in ms
    },
});

client.on('connect', log('connect', true));
client.on('ready', log('ready', true));
client.on('reconnecting', log('reconnecting', true));
client.on('error', log('error', true));
client.on('end', log('end', true));

要完整运行示例,请克隆node-cheat并运行node connect-retry.js


-2

添加到上面的答案。小改动。提供的回调应该是一个方法名,而不是执行方法本身。像下面这样:

function redisCallbackHandler(message){
    console.log("Redis:"+ message);
}

var redis = require("redis");
var redisclient = redis.createClient();
redisclient.on('connect', redisCallbackHandler);
redisclient.on('ready', redisCallbackHandler);
redisclient.on('reconnecting', redisCallbackHandler);
redisclient.on('error', redisCallbackHandler);
redisclient.on('end', redisCallbackHandler);

请检查上面的日志函数。它的函数返回值用作回调引用。 - Tamil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接