From 0dcb768e2e418b9dd3fa7feaf01ad85cb01521ef Mon Sep 17 00:00:00 2001 From: luin Date: Sun, 7 Feb 2016 23:41:21 +0800 Subject: [PATCH] fix(cluster): fix not connecting to the unknown nodes --- lib/cluster/connection_pool.js | 1 + lib/cluster/index.js | 5 +++-- test/functional/cluster.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/cluster/connection_pool.js b/lib/cluster/connection_pool.js index 26de8287..5051334c 100644 --- a/lib/cluster/connection_pool.js +++ b/lib/cluster/connection_pool.js @@ -23,6 +23,7 @@ ConnectionPool.prototype.findOrCreate = function (node, readOnly) { node.port = node.port || 6379; node.host = node.host || '127.0.0.1'; node.key = node.key || node.host + ':' + node.port; + readOnly = Boolean(readOnly); if (this.specifiedOptions[node.key]) { _.assign(node, this.specifiedOptions[node.key]); diff --git a/lib/cluster/index.js b/lib/cluster/index.js index 68a69c6f..8925d4d2 100644 --- a/lib/cluster/index.js +++ b/lib/cluster/index.js @@ -71,10 +71,10 @@ function Cluster(startupNodes, options) { var _this = this; this.connectionPool.on('-node', function (redis) { - _this.emit('-node'); if (_this.subscriber === redis) { _this.selectSubscriber(); } + _this.emit('-node'); }); this.connectionPool.on('+node', function (redis) { _this.emit('+node', redis); @@ -84,7 +84,6 @@ function Cluster(startupNodes, options) { }); this.slots = []; - this.retryAttempts = 0; this.resetOfflineQueue(); @@ -430,6 +429,8 @@ Cluster.prototype.sendCommand = function (command, stream, node) { } else { _this.slots[slot] = [key]; } + var splitKey = key.split(':'); + _this.connectionPool.findOrCreate({ host: splitKey[0], port: Number(splitKey[1]) }); tryConnection(); _this.refreshSlotsCache(); }, diff --git a/test/functional/cluster.js b/test/functional/cluster.js index 9402eb6a..edc41fba 100644 --- a/test/functional/cluster.js +++ b/test/functional/cluster.js @@ -338,6 +338,36 @@ describe('cluster', function () { }); }); + it('should be able to redirect a command to a unknown node', function (done) { + var slotTable = [ + [0, 16383, ['127.0.0.1', 30001]] + ]; + var node1 = new MockServer(30001, function (argv) { + if (argv[0] === 'cluster' && argv[1] === 'slots') { + return slotTable; + } + if (argv[0] === 'get' && argv[1] === 'foo') { + return new Error('MOVED ' + utils.calcSlot('foo') + ' 127.0.0.1:30002'); + } + }); + var node2 = new MockServer(30002, function (argv) { + if (argv[0] === 'cluster' && argv[1] === 'slots') { + return slotTable; + } + if (argv[0] === 'get' && argv[1] === 'foo') { + return 'bar'; + } + }); + var cluster = new Redis.Cluster([ + { host: '127.0.0.1', port: '30001' } + ], { lazyConnect: false }); + cluster.get('foo', function (err, res) { + expect(res).to.eql('bar'); + cluster.disconnect(); + disconnect([node1, node2], done); + }); + }); + it('should auto redirect the command within a pipeline', function (done) { var moved = false; var times = 0;