Skip to content

Commit

Permalink
Avoid retrying the last server on reconnect
Browse files Browse the repository at this point in the history
Signed-off-by: Colin Sullivan <[email protected]>
  • Loading branch information
ColinSullivan1 committed May 13, 2020
1 parent 8fdccec commit 17eda5a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
20 changes: 15 additions & 5 deletions src/main/java/io/nats/client/impl/NatsConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ void connect(boolean reconnectOnConnect) throws InterruptedException, IOExceptio

timeTrace(trace, "starting connect loop");

Collection<String> serversToTry = buildServerList();
Collection<String> serversToTry = buildServerList(false);
for (String serverURI : serversToTry) {
if (isClosed()) {
break;
Expand Down Expand Up @@ -263,7 +263,7 @@ void reconnect() throws InterruptedException {
boolean doubleAuthError = false;

while (!isConnected() && !isClosed() && !this.isClosing()) {
Collection<String> serversToTry = buildServerList();
Collection<String> serversToTry = buildServerList(true);

for (String server : serversToTry) {
if (isClosed()) {
Expand Down Expand Up @@ -1643,7 +1643,7 @@ void waitForReconnectTimeout() {
this.reconnectWaiter.complete(Boolean.TRUE);
}

Collection<String> buildServerList() {
Collection<String> buildServerList(boolean isReconnecting) {
ArrayList<String> reconnectList = new ArrayList<>();

reconnectList.addAll(getServers());
Expand All @@ -1652,8 +1652,18 @@ Collection<String> buildServerList() {
return reconnectList;
}

Collections.shuffle(reconnectList);

if (!isReconnecting) {
Collections.shuffle(reconnectList);
} else {
// Remove the current (first) server from the list, shuffle if it makes sense,
// and then add it to the end of the list. This prevents the client
// from immediately reconnecting to a server it just lost connection with.
String s = reconnectList.remove(0);
if (reconnectList.size() > 1) {
Collections.shuffle(reconnectList);
}
reconnectList.add(s);
}
return reconnectList;
}

Expand Down
3 changes: 1 addition & 2 deletions src/test/java/io/nats/client/impl/ReconnectTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,6 @@ public void testReconnectToSecondServer() throws Exception {
}
}


@Test
public void testNoRandomizeReconnectToSecondServer() throws Exception {
NatsConnection nc = null;
Expand Down Expand Up @@ -615,7 +614,7 @@ public void testReconnectNoIPTLSConnection() throws Exception {
server(ts.getURI()).
secure().
connectionListener(handler).
maxReconnects(10). // we get multiples for some, so need enough
maxReconnects(20). // we get multiples for some, so need enough
reconnectWait(Duration.ofMillis(100)).
connectionTimeout(Duration.ofSeconds(5)).
noRandomize().
Expand Down

0 comments on commit 17eda5a

Please sign in to comment.