public class RedisClusterClient extends AbstractRedisClient
getPartitions()
method.
Connections to the cluster members are opened on the first access to the cluster node and managed by the
StatefulRedisClusterConnection. You should not use transactional commands on cluster connections since MULTI,
EXEC and DISCARD have no key and cannot be assigned to a particular node. A cluster connection uses a default
connection to run non-keyed commands.
The Redis cluster client provides a sync, async and reactive API.
Connections to particular nodes can be obtained by StatefulRedisClusterConnection.getConnection(String) providing the
node id or StatefulRedisClusterConnection.getConnection(String, int) by host and port.
Multiple keys operations have to operate on a key that hashes to the same slot. Following commands do not need to follow that rule since they are pipelined according to its hash value to multiple nodes in parallel on the sync, async and, reactive API:
DELUNLINKMGETRedisStringAsyncCommands.mget(KeyValueStreamingChannel, Object[])) MGET with streaming}MSETMSETNX
Following commands on the Cluster sync, async and, reactive API are implemented with a Cluster-flavor:
RedisAdvancedClusterAsyncCommands.clientSetname(Object)ExecutesCLIENT SETon all connections and initializes new connections with theclientName.RedisAdvancedClusterAsyncCommands.flushall()RunFLUSHALLon all upstream nodes.RedisAdvancedClusterAsyncCommands.flushdb()ExecutesFLUSHDBon all upstream nodes.RedisAdvancedClusterAsyncCommands.keys(Object)ExecutesKEYSon all.RedisAdvancedClusterAsyncCommands.randomkey()Returns a random key from a random upstream node.RedisAdvancedClusterAsyncCommands.scriptFlush()ExecutesSCRIPT FLUSHon all nodes.RedisAdvancedClusterAsyncCommands.scriptKill()ExecutesSCRIPT KILLon all nodes.RedisAdvancedClusterAsyncCommands.shutdown(boolean)ExecutesSHUTDOWNon all nodes.RedisAdvancedClusterAsyncCommands.scan()Executes aSCANon all nodes according toReadFrom. The resulting cursor must be reused across theSCANto scan iteratively across the whole cluster.
Cluster commands can be issued to multiple hosts in parallel by using the NodeSelectionSupport API. A set of nodes is
selected using a Predicate and commands can be issued to the node selection
AsyncExecutions<String> ping = commands.upstream().commands().ping(); Collection<RedisClusterNode> nodes = ping.nodes(); nodes.stream().forEach(redisClusterNode -> ping.get(redisClusterNode));
RedisClusterClient is an expensive resource. Reuse this instance or share external ClientResources as much as
possible.- Since:
- 3.0
- Author:
- Mark Paluch
- See Also:
RedisURI,StatefulRedisClusterConnection,RedisCodec,ClusterClientOptions,ClientResources
-
Field Summary
Fields inherited from class io.lettuce.core.AbstractRedisClient
channels, closeableResources, connectionEvents -
Constructor Summary
Constructors Modifier Constructor Description protectedRedisClusterClient()Non-private constructor to makeRedisClusterClientproxyable.protectedRedisClusterClient(ClientResources clientResources, Iterable<RedisURI> redisURIs)Initialize the client with a list of cluster URI's. -
Method Summary
Modifier and Type Method Description StatefulRedisClusterConnection<String,String>connect()Connect to a Redis Cluster and treat keys and values as UTF-8 strings.<K, V> StatefulRedisClusterConnection<K,V>connect(RedisCodec<K,V> codec)Connect to a Redis Cluster.<K, V> CompletableFuture<StatefulRedisClusterConnection<K,V>>connectAsync(RedisCodec<K,V> codec)Connect asynchronously to a Redis Cluster.StatefulRedisClusterPubSubConnection<String,String>connectPubSub()Connect to a Redis Cluster using pub/sub connections and treat keys and values as UTF-8 strings.<K, V> StatefulRedisClusterPubSubConnection<K,V>connectPubSub(RedisCodec<K,V> codec)Connect to a Redis Cluster using pub/sub connections.<K, V> CompletableFuture<StatefulRedisClusterPubSubConnection<K,V>>connectPubSubAsync(RedisCodec<K,V> codec)Connect asynchronously to a Redis Cluster using pub/sub connections.static RedisClusterClientcreate(RedisURI redisURI)Create a new client that connects to the supplieduriwith defaultClientResources.static RedisClusterClientcreate(ClientResources clientResources, RedisURI redisURI)Create a new client that connects to the supplieduriwith sharedClientResources.static RedisClusterClientcreate(ClientResources clientResources, Iterable<RedisURI> redisURIs)Create a new client that connects to the supplieduriwith sharedClientResources.static RedisClusterClientcreate(ClientResources clientResources, String uri)Create a new client that connects to the supplied uri with sharedClientResources.You need to shut down theClientResourcesupon shutting down your application.static RedisClusterClientcreate(Iterable<RedisURI> redisURIs)Create a new client that connects to the supplieduriwith defaultClientResources.static RedisClusterClientcreate(String uri)Create a new client that connects to the supplied uri with defaultClientResources.protected ClusterTopologyRefreshcreateTopologyRefresh()Template method to createClusterTopologyRefresh.protected PartitionsdeterminePartitions(Partitions current, Map<RedisURI,Partitions> topologyViews)Determines atopology viewbased on the current and the obtain topology views.protected <T extends Closeable>
voidforEachCloseable(Predicate<? super Closeable> selector, Consumer<T> function)protected voidforEachClusterConnection(Consumer<StatefulRedisClusterConnectionImpl<?,?>> function)Apply aConsumerofStatefulRedisClusterConnectionImplto all active connections.protected voidforEachClusterPubSubConnection(Consumer<io.lettuce.core.cluster.StatefulRedisClusterPubSubConnectionImpl<?,?>> function)Apply aConsumerofStatefulRedisClusterPubSubConnectionImplto all active connections.protected RedisURIgetFirstUri()Returns the firstRedisURIconfigured with thisRedisClusterClientinstance.protected Iterable<RedisURI>getInitialUris()PartitionsgetPartitions()Retrieve the cluster view.protected Mono<SocketAddress>getSocketAddressSupplier(Supplier<Partitions> partitionsSupplier, Function<Partitions,Collection<RedisClusterNode>> sortFunction)Returns aSupplierforconnection points.protected Iterable<RedisURI>getTopologyRefreshSource()Returns the seedRedisURIfor the topology refreshing.protected CompletableFuture<Partitions>initializePartitions()protected PartitionsloadPartitions()Retrieve partitions.protected CompletableFuture<Partitions>loadPartitionsAsync()Retrieve partitions.protected <V, K> StatefulRedisClusterConnectionImpl<K,V>newStatefulRedisClusterConnection(RedisChannelWriter channelWriter, ClusterPushHandler pushHandler, RedisCodec<K,V> codec, Duration timeout)Create a new instance ofStatefulRedisClusterConnectionImplor a subclass.protected <K, V> StatefulRedisConnectionImpl<K,V>newStatefulRedisConnection(RedisChannelWriter channelWriter, PushHandler pushHandler, RedisCodec<K,V> codec, Duration timeout)Create a new instance ofStatefulRedisConnectionImplor a subclass.protected RedisCodec<String,String>newStringStringCodec()voidrefreshPartitions()Refresh partitions and re-initialize the routing table.CompletionStage<Void>refreshPartitionsAsync()Asynchronously reload partitions and re-initialize the distribution table.voidreloadPartitions()Deprecated.since 6.0.voidsetOptions(ClusterClientOptions clientOptions)Set theClusterClientOptionsfor the client.voidsetPartitions(Partitions partitions)Sets the new cluster topology.CompletableFuture<Void>shutdownAsync(long quietPeriod, long timeout, TimeUnit timeUnit)Shutdown this client and close all open connections asynchronously.protected static <T> CompletableFuture<T>transformAsyncConnectionException(CompletionStage<T> future, Iterable<RedisURI> target)protected voidupdatePartitionsInConnections()protected booleanuseDynamicRefreshSources()Returnstrueifdynamic refresh sourcesare enabled.Methods inherited from class io.lettuce.core.AbstractRedisClient
addListener, addListener, channelType, connectionBuilder, createHandshake, getChannelCount, getCommandListeners, getConnection, getConnection, getDefaultTimeout, getOptions, getResourceCount, getResources, initializeChannelAsync, removeListener, removeListener, setDefaultTimeout, setDefaultTimeout, setOptions, shutdown, shutdown, shutdown, shutdownAsync
-
Constructor Details
-
RedisClusterClient
protected RedisClusterClient()Non-private constructor to makeRedisClusterClientproxyable. -
RedisClusterClient
Initialize the client with a list of cluster URI's. All uris are tried in sequence for connecting initially to the cluster. If any uri is successful for connection, the others are not tried anymore. The initial uri is needed to discover the cluster structure for distributing the requests.- Parameters:
clientResources- the client resources. Ifnull, the client will create a new dedicated instance of client resources and keep track of them.redisURIs- iterable of initialcluster URIs. Must not benulland not empty.
-
-
Method Details
-
create
Create a new client that connects to the supplieduriwith defaultClientResources. You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
redisURI- the Redis URI, must not benull- Returns:
- a new instance of
RedisClusterClient
-
create
Create a new client that connects to the supplieduriwith defaultClientResources. You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
redisURIs- one or more Redis URI, must not benulland not empty.- Returns:
- a new instance of
RedisClusterClient
-
create
Create a new client that connects to the supplied uri with defaultClientResources. You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
uri- the Redis URI, must not be empty ornull.- Returns:
- a new instance of
RedisClusterClient
-
create
Create a new client that connects to the supplieduriwith sharedClientResources. You need to shut down theClientResourcesupon shutting down your application.You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
clientResources- the client resources, must not benullredisURI- the Redis URI, must not benull- Returns:
- a new instance of
RedisClusterClient
-
create
Create a new client that connects to the supplied uri with sharedClientResources.You need to shut down theClientResourcesupon shutting down your application. You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
clientResources- the client resources, must not benulluri- the Redis URI, must not be empty ornull.- Returns:
- a new instance of
RedisClusterClient
-
create
public static RedisClusterClient create(ClientResources clientResources, Iterable<RedisURI> redisURIs)Create a new client that connects to the supplieduriwith sharedClientResources. You need to shut down theClientResourcesupon shutting down your application.You can connect to different Redis servers but you must supply aRedisURIon connecting.- Parameters:
clientResources- the client resources, must not benullredisURIs- one or more Redis URI, must not benulland not empty- Returns:
- a new instance of
RedisClusterClient
-
setOptions
Set theClusterClientOptionsfor the client.- Parameters:
clientOptions- client options for the client and connections that are created after setting the options
-
getPartitions
Retrieve the cluster view. Partitions are shared amongst all connections opened by this client instance.- Returns:
- the partitions.
-
getTopologyRefreshSource
Returns the seedRedisURIfor the topology refreshing. This method is called before each topology refresh to provide anIterableofRedisURIthat is used to perform the next topology refresh.Subclasses of
RedisClusterClientmay override that method. -
connect
Connect to a Redis Cluster and treat keys and values as UTF-8 strings.What to expect from this connection:
- A default connection is created to the node with the lowest latency
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Pub/sub commands are sent to the node that handles the slot derived from the pub/sub channel
- Returns:
- A new stateful Redis Cluster connection
-
connect
Connect to a Redis Cluster. Use the suppliedcodecto encode/decode keys and values.What to expect from this connection:
- A default connection is created to the node with the lowest latency
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Pub/sub commands are sent to the node that handles the slot derived from the pub/sub channel
- Type Parameters:
K- Key typeV- Value type- Parameters:
codec- Use this codec to encode/decode keys and values, must not benull- Returns:
- A new stateful Redis Cluster connection
-
connectAsync
public <K, V> CompletableFuture<StatefulRedisClusterConnection<K,V>> connectAsync(RedisCodec<K,V> codec)Connect asynchronously to a Redis Cluster. Use the suppliedcodecto encode/decode keys and values. Connecting asynchronously requires an initialized topology. CallgetPartitions()first, otherwise the connect will fail with aIllegalStateException.What to expect from this connection:
- A default connection is created to the node with the lowest latency
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Pub/sub commands are sent to the node that handles the slot derived from the pub/sub channel
- Type Parameters:
K- Key typeV- Value type- Parameters:
codec- Use this codec to encode/decode keys and values, must not benull- Returns:
- a
CompletableFuturethat is notified with the connection progress. - Since:
- 5.1
-
connectPubSub
Connect to a Redis Cluster using pub/sub connections and treat keys and values as UTF-8 strings.What to expect from this connection:
- A default connection is created to the node with the least number of clients
- Pub/sub commands are sent to the node with the least number of clients
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Returns:
- A new stateful Redis Cluster connection
-
connectPubSub
Connect to a Redis Cluster using pub/sub connections. Use the suppliedcodecto encode/decode keys and values.What to expect from this connection:
- A default connection is created to the node with the least number of clients
- Pub/sub commands are sent to the node with the least number of clients
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Type Parameters:
K- Key typeV- Value type- Parameters:
codec- Use this codec to encode/decode keys and values, must not benull- Returns:
- A new stateful Redis Cluster connection
-
connectPubSubAsync
public <K, V> CompletableFuture<StatefulRedisClusterPubSubConnection<K,V>> connectPubSubAsync(RedisCodec<K,V> codec)Connect asynchronously to a Redis Cluster using pub/sub connections. Use the suppliedcodecto encode/decode keys and values. Connecting asynchronously requires an initialized topology. CallgetPartitions()first, otherwise the connect will fail with aIllegalStateException.What to expect from this connection:
- A default connection is created to the node with the least number of clients
- Pub/sub commands are sent to the node with the least number of clients
- Keyless commands are send to the default connection
- Single-key keyspace commands are routed to the appropriate node
- Multi-key keyspace commands require the same slot-hash and are routed to the appropriate node
- Type Parameters:
K- Key typeV- Value type- Parameters:
codec- Use this codec to encode/decode keys and values, must not benull- Returns:
- a
CompletableFuturethat is notified with the connection progress. - Since:
- 5.1
-
newStatefulRedisConnection
protected <K, V> StatefulRedisConnectionImpl<K,V> newStatefulRedisConnection(RedisChannelWriter channelWriter, PushHandler pushHandler, RedisCodec<K,V> codec, Duration timeout)Create a new instance ofStatefulRedisConnectionImplor a subclass.Subclasses of
RedisClusterClientmay override that method.- Type Parameters:
K- Key-TypeV- Value Type- Parameters:
channelWriter- the channel writerpushHandler- the handler for push notificationscodec- codectimeout- default timeout- Returns:
- new instance of StatefulRedisConnectionImpl
-
newStatefulRedisClusterConnection
protected <V, K> StatefulRedisClusterConnectionImpl<K,V> newStatefulRedisClusterConnection(RedisChannelWriter channelWriter, ClusterPushHandler pushHandler, RedisCodec<K,V> codec, Duration timeout)Create a new instance ofStatefulRedisClusterConnectionImplor a subclass.Subclasses of
RedisClusterClientmay override that method.- Type Parameters:
K- Key-TypeV- Value Type- Parameters:
channelWriter- the channel writerpushHandler- the handler for push notificationscodec- codectimeout- default timeout- Returns:
- new instance of StatefulRedisClusterConnectionImpl
-
reloadPartitions
Deprecated.since 6.0. Renamed torefreshPartitions().Refresh partitions and re-initialize the routing table. -
refreshPartitions
public void refreshPartitions()Refresh partitions and re-initialize the routing table.- Since:
- 6.0
-
refreshPartitionsAsync
Asynchronously reload partitions and re-initialize the distribution table.- Returns:
- a
CompletionStagethat signals completion. - Since:
- 6.0
-
updatePartitionsInConnections
protected void updatePartitionsInConnections() -
initializePartitions
-
loadPartitions
Retrieve partitions. Nodes withinPartitionsare ordered by latency. Lower latency nodes come first.- Returns:
- Partitions
-
loadPartitionsAsync
Retrieve partitions. Nodes withinPartitionsare ordered by latency. Lower latency nodes come first.- Returns:
- future that emits
Partitionsupon a successful topology lookup. - Since:
- 6.0
-
determinePartitions
protected Partitions determinePartitions(Partitions current, Map<RedisURI,Partitions> topologyViews)Determines atopology viewbased on the current and the obtain topology views.- Parameters:
current- the current topology view. May benullifRedisClusterClienthas no topology view yet.topologyViews- the obtain topology views- Returns:
- the
topology viewto use.
-
setPartitions
Sets the new cluster topology. The partitions are not applied to existing connections.- Parameters:
partitions- partitions object
-
shutdownAsync
Shutdown this client and close all open connections asynchronously. The client should be discarded after calling shutdown.- Overrides:
shutdownAsyncin classAbstractRedisClient- Parameters:
quietPeriod- the quiet period as described in the documentationtimeout- the maximum amount of time to wait until the executor is shutdown regardless if a task was submitted during the quiet periodtimeUnit- the unit ofquietPeriodandtimeout- Since:
- 4.4
- See Also:
EventExecutorGroup.shutdownGracefully(long, long, TimeUnit)
-
getFirstUri
Returns the firstRedisURIconfigured with thisRedisClusterClientinstance.- Returns:
- the first
RedisURI.
-
getSocketAddressSupplier
protected Mono<SocketAddress> getSocketAddressSupplier(Supplier<Partitions> partitionsSupplier, Function<Partitions,Collection<RedisClusterNode>> sortFunction)Returns aSupplierforconnection points.- Parameters:
sortFunction- Sort function to enforce a specific order. The sort function must not change the order or the input parameter but create a new collection with the desired order, must not benull.- Returns:
Supplierforconnection points.
-
getInitialUris
- Returns:
- the initial
URIs
-
forEachClusterConnection
protected void forEachClusterConnection(Consumer<StatefulRedisClusterConnectionImpl<?,?>> function)Apply aConsumerofStatefulRedisClusterConnectionImplto all active connections.- Parameters:
function- theConsumer.
-
forEachClusterPubSubConnection
protected void forEachClusterPubSubConnection(Consumer<io.lettuce.core.cluster.StatefulRedisClusterPubSubConnectionImpl<?,?>> function)Apply aConsumerofStatefulRedisClusterPubSubConnectionImplto all active connections.- Parameters:
function- theConsumer.
-
forEachCloseable
protected <T extends Closeable> void forEachCloseable(Predicate<? super Closeable> selector, Consumer<T> function)- Type Parameters:
T-- Parameters:
function- theConsumer.
-
createTopologyRefresh
Template method to createClusterTopologyRefresh. Can be overriden by subclasses.- Returns:
- Since:
- 6.0.3
-
useDynamicRefreshSources
protected boolean useDynamicRefreshSources()Returnstrueifdynamic refresh sourcesare enabled.Subclasses of
RedisClusterClientmay override that method.- Returns:
trueif dynamic refresh sources are used.- See Also:
ClusterTopologyRefreshOptions.useDynamicRefreshSources()
-
newStringStringCodec
- Returns:
- a
Stringcodec. - See Also:
StringCodec.UTF8
-
transformAsyncConnectionException
protected static <T> CompletableFuture<T> transformAsyncConnectionException(CompletionStage<T> future, Iterable<RedisURI> target)
-