diff --git a/README.md b/README.md index 3b40c4cf9d2..885274570b1 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,8 @@ every command on a client. Nagle algorithm on the underlying socket. Setting this option to `false` can result in additional throughput at the cost of more latency. Most applications will want this set to `true`. * `socket_keepalive` defaults to `true`. Whether the keep-alive functionality is enabled on the underlying socket. +* `socket_connect_timeout` defaults to `null`. By default a connection attempts use the operating system's timeout, but +setting `socket_connect_timeout` will time-out the connection attempt after this many milliseconds instead. * `no_ready_check`: defaults to `false`. When a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server not respond to any commands. To work around this, `node_redis` has a "ready check" which sends the `INFO` command to the server. The response from the `INFO` command diff --git a/index.js b/index.js index 45b20823ab4..0c9ac2f03ee 100644 --- a/index.js +++ b/index.js @@ -81,6 +81,12 @@ exports.RedisClient = RedisClient; RedisClient.prototype.install_stream_listeners = function() { var self = this; + if (this.options.socket_connect_timeout > 0) { + this.stream.setTimeout(this.options.socket_connect_timeout, function () { + self.on_timeout(); + }); + } + this.stream.on("connect", function () { self.on_connect(); }); @@ -218,6 +224,18 @@ RedisClient.prototype.do_auth = function () { self.send_anyway = false; }; +RedisClient.prototype.on_timeout = function () { + if (this.connected || this.closing) { + // Only handle connection timeouts. + return; + } + + debug("Stream timeout " + this.address + " id " + this.connection_id); + + this.stream.end(); + this.connection_gone("timeout"); +}; + RedisClient.prototype.on_connect = function () { debug("Stream connected " + this.address + " id " + this.connection_id);