diff --git a/src/main/java/io/nats/client/impl/NatsConnection.java b/src/main/java/io/nats/client/impl/NatsConnection.java index a91ef57a3..cf42d2680 100644 --- a/src/main/java/io/nats/client/impl/NatsConnection.java +++ b/src/main/java/io/nats/client/impl/NatsConnection.java @@ -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"); @@ -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"); @@ -291,6 +294,7 @@ void reconnect() throws InterruptedException { break; } else if (isConnected()) { this.statistics.incrementReconnects(); + this.currentServer = server; break; } else { String err = connectError.get(); @@ -1652,8 +1656,18 @@ Collection 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; } 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().