From ef0b15e0e641098ce59c1a15042894fd55c63f8a Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Sat, 24 Nov 2018 13:59:56 +0100 Subject: [PATCH] Use Cluster write connections for read commands when using ReadFrom.MASTER #923 Lettuce now reuses master connections when ReadFrom is configured to MASTER (which is the default configuration). By reusing the master connection, we can reduce the number of used connections by up to 50% as we don't need an additional read connection while talking to the same node. --- .../cluster/PooledClusterConnectionProvider.java | 3 ++- .../PooledClusterConnectionProviderUnitTests.java | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/lettuce/core/cluster/PooledClusterConnectionProvider.java b/src/main/java/io/lettuce/core/cluster/PooledClusterConnectionProvider.java index 96356f4643..96299c24ca 100644 --- a/src/main/java/io/lettuce/core/cluster/PooledClusterConnectionProvider.java +++ b/src/main/java/io/lettuce/core/cluster/PooledClusterConnectionProvider.java @@ -104,9 +104,10 @@ public CompletableFuture> getConnectionAsync(Inten logger.debug("getConnection(" + intent + ", " + slot + ")"); } - if (intent == Intent.READ && readFrom != null) { + if (intent == Intent.READ && readFrom != null && readFrom != ReadFrom.MASTER) { return getReadConnection(slot); } + return getWriteConnection(slot).toCompletableFuture(); } diff --git a/src/test/java/io/lettuce/core/cluster/PooledClusterConnectionProviderUnitTests.java b/src/test/java/io/lettuce/core/cluster/PooledClusterConnectionProviderUnitTests.java index d3167bd331..0ed404f104 100644 --- a/src/test/java/io/lettuce/core/cluster/PooledClusterConnectionProviderUnitTests.java +++ b/src/test/java/io/lettuce/core/cluster/PooledClusterConnectionProviderUnitTests.java @@ -125,6 +125,21 @@ void shouldObtainConnection() { verifyNoMoreInteractions(connection); } + @Test + void shouldReuseMasterConnectionForReadFromMaster() { + + when(clientMock.connectToNodeAsync(eq(CODEC), eq("localhost:1"), any(), any())).thenReturn( + ConnectionFuture.from(socketAddressMock, CompletableFuture.completedFuture(nodeConnectionMock))); + + sut.setReadFrom(ReadFrom.MASTER); + + StatefulRedisConnection connection = sut.getConnection(Intent.READ, 1); + + assertThat(connection).isSameAs(nodeConnectionMock); + verify(connection).setAutoFlushCommands(true); + verifyNoMoreInteractions(connection); + } + @Test void shouldObtainConnectionReadFromSlave() {