poolConfig,
- Duration topologyRefreshPeriod, int maxAttempts) {
- // Same retry budget as the JedisCluster constructor used by Spring's JedisConnectionFactory.
- super(clusterNodes, clientConfig, poolConfig, topologyRefreshPeriod, maxAttempts,
- Duration.ofMillis((long) clientConfig.getSocketTimeoutMillis() * maxAttempts));
- }
-
- /**
- * Reloads the slot map from the cluster. Seed nodes are asked first, so this works even when every known node
- * address has changed. Returns immediately if another thread is already renewing it.
- */
- public void renewSlotCache() {
- ((ClusterConnectionProvider) provider).renewSlotCache();
- }
-
-}
diff --git a/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java b/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java
index f1efc0276a..ed2a253dac 100644
--- a/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java
+++ b/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java
@@ -6,26 +6,36 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
+import org.springframework.data.redis.util.RedisClientLibraryInfo;
import org.thingsboard.server.common.data.StringUtils;
+import redis.clients.jedis.ClientSetInfoConfig;
import redis.clients.jedis.Connection;
import redis.clients.jedis.DefaultJedisClientConfig;
+import redis.clients.jedis.DriverInfo;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisClientConfig;
-import redis.clients.jedis.JedisCluster;
+import redis.clients.jedis.RedisClusterClient;
+import redis.clients.jedis.providers.ClusterConnectionProvider;
import java.time.Duration;
import java.util.Set;
import java.util.stream.Collectors;
/**
- * Cluster connection factory that creates a {@link TbJedisCluster}, so the cache can renew the Jedis slot map after
- * a topology change, and the slot map is also refreshed in the background.
+ * Cluster connection factory whose Jedis slot map can be renewed on demand and is also refreshed in the background.
+ *
+ * Commands sent through the cluster command executor renew the slot map themselves, on MOVED and on repeated
+ * connection errors. Commands that need one node connection (WATCH/MULTI, a script pinned to one slot) borrow it
+ * through {@link RedisClusterClient#getConnectionFromSlot(int)}, which bypasses that executor. When such a command
+ * fails because the cluster topology changed, the caller must call {@link #renewSlotCache()}. Otherwise every later
+ * call goes to the old node again, and if that node's address is gone, it fails until the JVM restarts.
*/
public class TbJedisClusterConnectionFactory extends JedisConnectionFactory {
- private static final int DEFAULT_MAX_REDIRECTS = 5; // same default as JedisConnectionFactory#createCluster
+ private static final int DEFAULT_MAX_REDIRECTS = 5; // same default as JedisConnectionFactory#createRedisClusterClient
private final Duration topologyRefreshPeriod;
+ private volatile ClusterConnectionProvider connectionProvider;
/**
* @param topologyRefreshPeriod period of the background slot map refresh, or {@code null} to disable it
@@ -37,12 +47,33 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory {
}
@Override
- protected JedisCluster createCluster(RedisClusterConfiguration clusterConfig, GenericObjectPoolConfig poolConfig) {
+ protected RedisClusterClient createRedisClusterClient(RedisClusterConfiguration clusterConfig) {
Set nodes = clusterConfig.getClusterNodes().stream()
.map(node -> new HostAndPort(node.getHost(), node.getPort()))
.collect(Collectors.toSet());
int maxRedirects = clusterConfig.getMaxRedirects() != null ? clusterConfig.getMaxRedirects() : DEFAULT_MAX_REDIRECTS;
- return new TbJedisCluster(nodes, createClusterClientConfig(clusterConfig), poolConfig, topologyRefreshPeriod, maxRedirects);
+ JedisClientConfig clientConfig = createClusterClientConfig(clusterConfig);
+ GenericObjectPoolConfig poolConfig = getPoolConfig();
+ ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, clientConfig, poolConfig, topologyRefreshPeriod);
+
+ RedisClusterClient.Builder builder = RedisClusterClient.builder();
+ builder.nodes(nodes).clientConfig(clientConfig).maxAttempts(maxRedirects).poolConfig(poolConfig);
+ getClientConfiguration().getClientCustomizer().ifPresent(customizer -> customizer.customize(builder));
+ builder.connectionProvider(provider);
+ RedisClusterClient client = builder.build();
+ connectionProvider = provider;
+ return client;
+ }
+
+ /**
+ * Reloads the slot map from the cluster. Seed nodes are asked first, so this works even when every known node
+ * address has changed. Returns immediately if another thread is already renewing it, or if the factory is not started.
+ */
+ public void renewSlotCache() {
+ ClusterConnectionProvider provider = connectionProvider;
+ if (provider != null) {
+ provider.renewSlotCache();
+ }
}
/**
@@ -54,6 +85,9 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory {
clientConfiguration.getClientName().ifPresent(builder::clientName);
builder.connectionTimeoutMillis(Math.toIntExact(clientConfiguration.getConnectTimeout().toMillis()));
builder.socketTimeoutMillis(Math.toIntExact(clientConfiguration.getReadTimeout().toMillis()));
+ builder.clientSetInfoConfig(new ClientSetInfoConfig(DriverInfo.builder()
+ .addUpstreamDriver(RedisClientLibraryInfo.FRAMEWORK_NAME, RedisClientLibraryInfo.getVersion())
+ .build()));
builder.database(getDatabase());
if (StringUtils.isNotEmpty(clusterConfig.getUsername())) {
builder.user(clusterConfig.getUsername());
@@ -65,7 +99,7 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory {
clientConfiguration.getHostnameVerifier().ifPresent(builder::hostnameVerifier);
clientConfiguration.getSslParameters().ifPresent(builder::sslParameters);
}
- clientConfiguration.getCustomizer().ifPresent(customizer -> customizer.customize(builder));
+ clientConfiguration.getClientConfigCustomizer().ifPresent(customizer -> customizer.customize(builder));
return builder.build();
}
diff --git a/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java b/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java
index b3c77c0864..ab3b26c1c0 100644
--- a/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java
+++ b/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java
@@ -11,10 +11,10 @@ import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisScriptingCommands;
import org.springframework.data.redis.connection.ReturnType;
-import org.springframework.data.redis.connection.jedis.JedisClusterConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.exceptions.JedisConnectionException;
+import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.exceptions.JedisMovedDataException;
import java.nio.charset.StandardCharsets;
@@ -25,6 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -41,7 +42,8 @@ class RedisTbTransactionalCacheTest {
private static final String CACHE_NAME = "testCache";
- private JedisConnectionFactory connectionFactory;
+ private TbJedisClusterConnectionFactory connectionFactory;
+ private RedisConnection connection;
private RedisScriptingCommands scriptingCommands;
@Test
@@ -86,7 +88,7 @@ class RedisTbTransactionalCacheTest {
@Test
void givenClusterTopologyError_whenRetryOnClusterTopologyChange_thenRenewsSlotMapAndRetriesOnce() {
TestRedisCache cache = createCache("");
- TbJedisCluster cluster = mockCluster();
+ TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory();
AtomicInteger attempts = new AtomicInteger();
String result = cache.retryOnClusterTopologyChange(() -> {
@@ -104,7 +106,7 @@ class RedisTbTransactionalCacheTest {
@Test
void givenClusterTopologyErrorTwice_whenRetryOnClusterTopologyChange_thenThrowsAfterOneRetry() {
TestRedisCache cache = createCache("");
- TbJedisCluster cluster = mockCluster();
+ TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory();
AtomicInteger attempts = new AtomicInteger();
assertThatThrownBy(() -> cache.retryOnClusterTopologyChange(() -> {
@@ -119,7 +121,7 @@ class RedisTbTransactionalCacheTest {
@Test
void givenOtherError_whenRetryOnClusterTopologyChange_thenThrowsWithoutRenewing() {
TestRedisCache cache = createCache("");
- TbJedisCluster cluster = mockCluster();
+ TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory();
AtomicInteger attempts = new AtomicInteger();
assertThatThrownBy(() -> cache.retryOnClusterTopologyChange(() -> {
@@ -142,7 +144,20 @@ class RedisTbTransactionalCacheTest {
})).isInstanceOf(RedisConnectionFailureException.class);
assertThat(attempts).hasValue(1);
- verify(connectionFactory, never()).getClusterConnection();
+ verify(connectionFactory, never()).renewSlotCache();
+ }
+
+ @Test
+ void givenWatchFailsAndCloseFails_whenWatch_thenThrowsWatchErrorWithCloseErrorSuppressed() {
+ TestRedisCache cache = createCache("");
+ JedisConnectionException watchError = new JedisConnectionException("Failed to connect to 10.0.0.1:6379.");
+ JedisException closeError = new JedisException("Could not return the broken resource to the pool");
+ doThrow(watchError).when(connection).watch(any(byte[][].class));
+ doThrow(closeError).when(connection).close();
+
+ assertThatThrownBy(() -> cache.watch(new byte[][]{cache.getRawKey("myKey")}))
+ .isSameAs(watchError)
+ .hasSuppressedException(closeError);
}
@Test
@@ -155,18 +170,14 @@ class RedisTbTransactionalCacheTest {
assertThat(RedisTbTransactionalCache.isClusterTopologyError(new IllegalStateException())).isFalse();
}
- private TbJedisCluster mockCluster() {
- TbJedisCluster cluster = mock(TbJedisCluster.class);
- JedisClusterConnection clusterConnection = mock(JedisClusterConnection.class);
- when(clusterConnection.getNativeConnection()).thenReturn(cluster);
+ private TbJedisClusterConnectionFactory mockClusterAwareFactory() {
when(connectionFactory.isRedisClusterAware()).thenReturn(true);
- when(connectionFactory.getClusterConnection()).thenReturn(clusterConnection);
- return cluster;
+ return connectionFactory;
}
private TestRedisCache createCache(String keyPrefix) {
- connectionFactory = mock(JedisConnectionFactory.class);
- RedisConnection connection = mock(RedisConnection.class);
+ connectionFactory = mock(TbJedisClusterConnectionFactory.class);
+ connection = mock(RedisConnection.class);
scriptingCommands = mock(RedisScriptingCommands.class);
when(connectionFactory.isRedisClusterAware()).thenReturn(false);
when(connectionFactory.getConnection()).thenReturn(connection);
diff --git a/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java b/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java
index 3ae1764cfb..3c52a5f93d 100644
--- a/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java
+++ b/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java
@@ -5,7 +5,9 @@ package org.thingsboard.server.cache;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
+import org.springframework.data.redis.connection.jedis.JedisClusterConnection;
import redis.clients.jedis.JedisClientConfig;
+import redis.clients.jedis.RedisClusterClient;
import javax.net.ssl.SSLSocketFactory;
import java.time.Duration;
@@ -60,4 +62,23 @@ class TbJedisClusterConnectionFactoryTest {
assertThat(config.getSslSocketFactory()).isSameAs(sslSocketFactory);
}
+ @Test
+ void whenStart_thenClusterClientIsBuiltThroughOverride() {
+ RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(List.of("127.0.0.1:6379"));
+ RedisClusterClient client = mock(RedisClusterClient.class);
+ var factory = new TbJedisClusterConnectionFactory(clusterConfig, JedisClientConfiguration.defaultConfiguration(), null) {
+ @Override
+ protected RedisClusterClient createRedisClusterClient(RedisClusterConfiguration config) {
+ return client;
+ }
+ };
+
+ factory.start();
+ try {
+ assertThat(((JedisClusterConnection) factory.getClusterConnection()).getNativeConnection()).isSameAs(client);
+ } finally {
+ factory.stop();
+ }
+ }
+
}
diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml
index fd8a22fd53..be18ecd519 100644
--- a/common/coap-server/pom.xml
+++ b/common/coap-server/pom.xml
@@ -49,8 +49,8 @@
spring-context