Skip to content

Commit

Permalink
Merge pull request #311 from nats-io/fix-reconnect
Browse files Browse the repository at this point in the history
Avoid retrying the last server on reconnect.
  • Loading branch information
sasbury authored May 14, 2020
2 parents 8fdccec + 2393b9e commit 5a90bfc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
18 changes: 16 additions & 2 deletions src/main/java/io/nats/client/impl/NatsConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ class NatsConnection implements Connection {
private ExecutorService executor;
private ExecutorService connectExecutor;

private String currentServer = null;

NatsConnection(Options options) {
boolean trace = options.isTraceConnection();
timeTrace(trace, "creating connection object");
Expand Down Expand Up @@ -206,6 +208,7 @@ void connect(boolean reconnectOnConnect) throws InterruptedException, IOExceptio
tryToConnect(serverURI, System.nanoTime());

if (isConnected()) {
this.currentServer = serverURI;
break;
} else {
timeTrace(trace, "setting status to disconnected");
Expand Down Expand Up @@ -291,6 +294,7 @@ void reconnect() throws InterruptedException {
break;
} else if (isConnected()) {
this.statistics.incrementReconnects();
this.currentServer = server;
break;
} else {
String err = connectError.get();
Expand Down Expand Up @@ -1652,8 +1656,18 @@ Collection<String> buildServerList() {
return reconnectList;
}

Collections.shuffle(reconnectList);

if (currentServer == null) {
Collections.shuffle(reconnectList);
} else {
// Remove the current 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.
reconnectList.remove(this.currentServer);
if (reconnectList.size() > 1) {
Collections.shuffle(reconnectList);
}
reconnectList.add(this.currentServer);
}
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 5a90bfc

Please sign in to comment.