diff --git a/src/main/java/io/nats/client/impl/NatsConnection.java b/src/main/java/io/nats/client/impl/NatsConnection.java index a91ef57a3..eafe93b0d 100644 --- a/src/main/java/io/nats/client/impl/NatsConnection.java +++ b/src/main/java/io/nats/client/impl/NatsConnection.java @@ -192,7 +192,7 @@ void connect(boolean reconnectOnConnect) throws InterruptedException, IOExceptio timeTrace(trace, "starting connect loop"); - Collection serversToTry = buildServerList(); + Collection serversToTry = buildServerList(false); for (String serverURI : serversToTry) { if (isClosed()) { break; @@ -263,7 +263,7 @@ void reconnect() throws InterruptedException { boolean doubleAuthError = false; while (!isConnected() && !isClosed() && !this.isClosing()) { - Collection serversToTry = buildServerList(); + Collection serversToTry = buildServerList(true); for (String server : serversToTry) { if (isClosed()) { @@ -1643,7 +1643,7 @@ void waitForReconnectTimeout() { this.reconnectWaiter.complete(Boolean.TRUE); } - Collection buildServerList() { + Collection buildServerList(boolean isReconnecting) { ArrayList reconnectList = new ArrayList<>(); reconnectList.addAll(getServers()); @@ -1652,8 +1652,18 @@ Collection 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; } diff --git a/src/test/java/io/nats/client/impl/ReconnectTests.java b/src/test/java/io/nats/client/impl/ReconnectTests.java index 850f2eb93..fe39fff17 100644 --- a/src/test/java/io/nats/client/impl/ReconnectTests.java +++ b/src/test/java/io/nats/client/impl/ReconnectTests.java @@ -341,7 +341,6 @@ public void testReconnectToSecondServer() throws Exception { } } - @Test public void testNoRandomizeReconnectToSecondServer() throws Exception { NatsConnection nc = null; @@ -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().