@@ -132,7 +132,7 @@ def get_random_connection
132132 node = @nodes [ node_id ]
133133 conn = Redis . new ( node [ :host ] , node [ :port ] )
134134 if conn . ping == "PONG"
135- close_existing_connection
135+ close_existing_connections
136136 @connections [ node_id ] = conn
137137 return conn
138138 else
@@ -152,25 +152,35 @@ def get_connection_by(slot)
152152 node_id = @slots [ slot ]
153153 return get_random_connection if node_id . nil?
154154
155- if ! @connections [ node_id ]
156- close_existing_connection
155+ unless @connections [ node_id ]
156+ close_existing_connections
157157 node = @nodes [ node_id ]
158- @connections [ node_id ] = Redis . new ( node [ :host ] , node [ :port ] )
158+ begin
159+ @connections [ node_id ] = Redis . new ( node [ :host ] , node [ :port ] )
160+ rescue
161+ return get_random_connection
162+ end
159163 end
160164
161165 @connections [ node_id ]
162166 end
163167
164- def close_existing_connection
168+ def close_connection ( conn )
169+ raise TypeError unless conn . instance_of? ( Redis )
170+ conn . close
171+ @connection . delete_if { |i , c | c . host == conn . host && c . port == conn . port }
172+ end
173+ 174+ def close_existing_connections
165175 while @connections . length > @max_cached_connections
166- id , conn = @connections . shift
167- conn . close
176+ conn = @connections . shift
177+ close_connection ( conn )
168178 end
169179 end
170180
171181 def close_all_connections
172- @connections . each do |id , conn |
173- conn . close
182+ @connections . each do |i , c |
183+ close_connection ( conn )
174184 end
175185 @connections . clear
176186 end
0 commit comments