@@ -110,12 +110,17 @@ function Client (options) {
110
110
EventEmitter . call ( this , options )
111
111
112
112
var self = this
113
- var _url
114
- if ( options . url ) { _url = url . parse ( options . url ) }
115
- this . host = _url ? _url . hostname : undefined
116
- this . port = _url ? _url . port : false
117
- this . secure = _url ? _url . secure : false
118
- this . url = _url
113
+ this . servers = [ ]
114
+ if ( options . url ) {
115
+ var [ , protocol , hosts , path ] = options . url . match ( / ^ ( [ a - z A - Z ] + : \/ \/ ) ( [ ^ / ] * ) ( .* ) / )
116
+
117
+ hosts . split ( ',' ) . forEach ( ( host ) => {
118
+ this . servers . push ( url . parse ( `${ protocol } ${ host } ${ path } ` ) )
119
+ } )
120
+ }
121
+
122
+ // select random server at the start
123
+ this . nextServer = Math . floor ( Math . random ( ) * this . servers . length )
119
124
this . tlsOptions = options . tlsOptions
120
125
this . socketPath = options . socketPath || false
121
126
@@ -792,6 +797,8 @@ Client.prototype.connect = function connect () {
792
797
793
798
// Establish basic socket connection
794
799
function connectSocket ( cb ) {
800
+ self . nextServer = ( self . nextServer + 1 ) % self . servers . length
801
+ self . url = self . servers [ self . nextServer ]
795
802
cb = once ( cb )
796
803
797
804
function onResult ( err , res ) {
@@ -820,12 +827,13 @@ Client.prototype.connect = function connect () {
820
827
setupClient ( cb )
821
828
}
822
829
823
- var port = ( self . port || self . socketPath )
830
+ var port = ( self . servers . length && self . servers [ self . nextServer ] . port ) || self . socketPath
831
+ var hostname = ( self . servers . length && self . servers [ self . nextServer ] . hostname ) || undefined
824
832
if ( self . secure ) {
825
- socket = tls . connect ( port , self . host , self . tlsOptions )
833
+ socket = tls . connect ( port , hostname , self . tlsOptions )
826
834
socket . once ( 'secureConnect' , onConnect )
827
835
} else {
828
- socket = net . connect ( port , self . host )
836
+ socket = net . connect ( port , hostname )
829
837
socket . once ( 'connect' , onConnect )
830
838
}
831
839
socket . once ( 'error' , onResult )
@@ -975,6 +983,9 @@ Client.prototype.connect = function connect () {
975
983
maxDelay : this . reconnect . maxDelay
976
984
} )
977
985
failAfter = this . reconnect . failAfter
986
+ if ( this . servers . length > 1 && failAfter ) {
987
+ failAfter *= this . servers . length
988
+ }
978
989
} else {
979
990
retry = backoff . exponential ( {
980
991
initialDelay : 1 ,
0 commit comments