Browse Source

Build the Redis cluster client through the slot-map-renewing factory under Spring Data Redis 4.1

pull/16341/head
Viacheslav Klimov 2 weeks ago
parent
commit
7db4af6812
Failed to extract signature
  1. 27
      common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java
  2. 44
      common/cache/src/main/java/org/thingsboard/server/cache/TbJedisCluster.java
  3. 48
      common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java
  4. 39
      common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java
  5. 21
      common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java

27
common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java

@ -21,12 +21,9 @@ import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.thingsboard.server.common.data.FstStatsService;
import redis.clients.jedis.Connection;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.RedisClusterClient;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisRedirectionException;
import redis.clients.jedis.util.JedisClusterCRC16;
@ -244,7 +241,7 @@ public abstract class RedisTbTransactionalCache<K extends Serializable, V extend
return connectionFactory.getConnection();
}
int slotNum = JedisClusterCRC16.getSlot(rawKey);
Jedis jedis = new Jedis(getConnectionFromSlot(getNativeCluster(), slotNum));
Jedis jedis = new Jedis(getNativeCluster().getConnectionFromSlot(slotNum));
JedisConnection jedisConnection = new JedisConnection(jedis, MOCK_POOL, jedis.getDB());
jedisConnection.setConvertPipelineAndTxResults(connectionFactory.getConvertPipelineAndTxResults());
@ -252,14 +249,6 @@ public abstract class RedisTbTransactionalCache<K extends Serializable, V extend
return jedisConnection;
}
private static Connection getConnectionFromSlot(UnifiedJedis cluster, int slotNum) {
return switch (cluster) {
case JedisCluster jedisCluster -> jedisCluster.getConnectionFromSlot(slotNum);
case RedisClusterClient clusterClient -> clusterClient.getConnectionFromSlot(slotNum);
default -> throw new IllegalStateException("Unsupported Redis cluster client: " + cluster.getClass());
};
}
protected RedisConnection watch(byte[][] rawKeysList) {
return retryOnClusterTopologyChange(() -> doWatch(rawKeysList));
}
@ -270,7 +259,11 @@ public abstract class RedisTbTransactionalCache<K extends Serializable, V extend
connection.watch(rawKeysList);
connection.multi();
} catch (Exception e) {
connection.close();
try {
connection.close();
} catch (Exception closeException) {
e.addSuppressed(closeException);
}
throw e;
}
return connection;
@ -286,11 +279,11 @@ public abstract class RedisTbTransactionalCache<K extends Serializable, V extend
return command.get();
} catch (RuntimeException e) {
if (!connectionFactory.isRedisClusterAware() || !isClusterTopologyError(e)
|| !(getNativeCluster() instanceof TbJedisCluster cluster)) {
|| !(connectionFactory instanceof TbJedisClusterConnectionFactory clusterConnectionFactory)) {
throw e;
}
log.warn("[{}] Redis cluster topology changed, renewing the slot map and retrying: {}", cacheName, e.getMessage());
cluster.renewSlotCache();
clusterConnectionFactory.renewSlotCache();
return command.get();
}
}
@ -300,8 +293,8 @@ public abstract class RedisTbTransactionalCache<K extends Serializable, V extend
|| e instanceof RedisConnectionFailureException || e instanceof ClusterRedirectException;
}
private UnifiedJedis getNativeCluster() {
return ((JedisClusterConnection) connectionFactory.getClusterConnection()).getNativeConnection();
private RedisClusterClient getNativeCluster() {
return (RedisClusterClient) ((JedisClusterConnection) connectionFactory.getClusterConnection()).getNativeConnection();
}
protected byte[] getRawKey(K key) {

44
common/cache/src/main/java/org/thingsboard/server/cache/TbJedisCluster.java

@ -1,44 +0,0 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.cache;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Connection;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisClientConfig;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.providers.ClusterConnectionProvider;
import java.time.Duration;
import java.util.Set;
/**
* {@link JedisCluster} whose slot map can be renewed on demand.
* <p>
* 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 #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 TbJedisCluster extends JedisCluster {
/**
* @param topologyRefreshPeriod period of the background slot map refresh, or {@code null} to disable it
*/
public TbJedisCluster(Set<HostAndPort> clusterNodes, JedisClientConfig clientConfig, GenericObjectPoolConfig<Connection> 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();
}
}

48
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.
* <p>
* 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<Connection> poolConfig) {
protected RedisClusterClient createRedisClusterClient(RedisClusterConfiguration clusterConfig) {
Set<HostAndPort> 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<Connection> 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();
}

39
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);

21
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();
}
}
}

Loading…
Cancel
Save