Node JS Redis Client Connection Retry
目前,我正在使用https://github.com/mranney/node_redis作为我的节点redis客户端。
我尝试连接到Redis,一旦连接成功,我就手动停止了Redis服务器以查看
在使用
1 2 3 | [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服务器是否已启动?
我无法重现。 您可以尝试使用此代码,停止Redis服务器并检查日志输出吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); } } |
答案@ 2020年2月
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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并运行
添加到上面的答案。 小变化。 提供的回调应为方法名称,而不是执行方法本身。 如下所示:
1 2 3 4 5 6 7 8 9 10 11 | 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); |