pub struct ClusterClientBuilder { /* private fields */ }cluster only.Expand description
Used to configure and build a ClusterClient.
Implementations§
Source§impl ClusterClientBuilder
impl ClusterClientBuilder
Sourcepub fn new<T>(
initial_nodes: impl IntoIterator<Item = T>,
) -> ClusterClientBuilderwhere
T: IntoConnectionInfo,
pub fn new<T>(
initial_nodes: impl IntoIterator<Item = T>,
) -> ClusterClientBuilderwhere
T: IntoConnectionInfo,
Creates a new ClusterClientBuilder with the provided initial_nodes.
This is the same as ClusterClient::builder(initial_nodes).
Sourcepub fn build(self) -> Result<ClusterClient, RedisError>
pub fn build(self) -> Result<ClusterClient, RedisError>
Creates a new ClusterClient from the parameters.
This does not create connections to the Redis Cluster, but only performs some basic checks on the initial nodes’ URLs and passwords/usernames.
When the tls-rustls feature is enabled and TLS credentials are provided, they are set for
each cluster connection.
§Errors
Upon failure to parse initial nodes or if the initial nodes have different passwords or usernames, an error is returned.
Sourcepub fn password(self, password: impl AsRef<str>) -> ClusterClientBuilder
pub fn password(self, password: impl AsRef<str>) -> ClusterClientBuilder
Sets password for the new ClusterClient.
Sourcepub fn username(self, username: impl AsRef<str>) -> ClusterClientBuilder
pub fn username(self, username: impl AsRef<str>) -> ClusterClientBuilder
Sets username for the new ClusterClient.
Sourcepub fn retries(self, retries: u32) -> ClusterClientBuilder
pub fn retries(self, retries: u32) -> ClusterClientBuilder
Sets number of retries for the new ClusterClient.
Sourcepub fn max_retry_wait(self, max_wait: u64) -> ClusterClientBuilder
pub fn max_retry_wait(self, max_wait: u64) -> ClusterClientBuilder
Sets maximal wait time in millisceonds between retries for the new ClusterClient.
Sourcepub fn min_retry_wait(self, min_wait: u64) -> ClusterClientBuilder
pub fn min_retry_wait(self, min_wait: u64) -> ClusterClientBuilder
Sets minimal wait time in millisceonds between retries for the new ClusterClient.
Sourcepub fn retry_wait_formula(
self,
factor: u64,
exponent_base: u64,
) -> ClusterClientBuilder
pub fn retry_wait_formula( self, factor: u64, exponent_base: u64, ) -> ClusterClientBuilder
Sets the factor and exponent base for the retry wait time. The formula for the wait is rand(min_wait_retry .. min(max_retry_wait , factor * exponent_base ^ retry))ms.
Sourcepub fn tls(self, tls: TlsMode) -> ClusterClientBuilder
Available on crate features tls-native-tls or tls-rustls only.
pub fn tls(self, tls: TlsMode) -> ClusterClientBuilder
tls-native-tls or tls-rustls only.Sets TLS mode for the new ClusterClient.
It is extracted from the first node of initial_nodes if not set.
Sourcepub fn danger_accept_invalid_hostnames(
self,
insecure: bool,
) -> ClusterClientBuilder
Available on crate features tls-native-tls or tls-rustls-insecure only.
pub fn danger_accept_invalid_hostnames( self, insecure: bool, ) -> ClusterClientBuilder
tls-native-tls or tls-rustls-insecure only.Configure hostname verification when connecting with TLS.
If insecure is true, this disables hostname verification, while
leaving other aspects of certificate checking enabled. This mode is
similar to what redis-cli does: TLS connections do check certificates,
but hostname errors are ignored.
§Warning
You should think very carefully before you use this method. If hostname verification is not used, any valid certificate for any site will be trusted for use from any other. This introduces a significant vulnerability to man-in-the-middle attacks.
Sourcepub fn certs(self, certificates: TlsCertificates) -> ClusterClientBuilder
Available on crate feature tls-rustls only.
pub fn certs(self, certificates: TlsCertificates) -> ClusterClientBuilder
tls-rustls only.Sets raw TLS certificates for the new ClusterClient.
When set, enforces the connection must be TLS secured.
All certificates must be provided as byte streams loaded from PEM files their consistency is
checked during build() call.
certificates-TlsCertificatesstructure containing:-
client_tls- OptionalClientTlsConfigcontaining byte streams forclient_cert- client’s byte stream containing client certificate in PEM formatclient_key- client’s byte stream containing private key in PEM format
-
root_cert- Optional byte stream yielding PEM formatted file for root certificates.
-
If ClientTlsConfig ( cert+key pair ) is not provided, then client-side authentication is not enabled.
If root_cert is not provided, then system root certificates are used instead.
Sourcepub fn read_from_replicas(self) -> ClusterClientBuilder
👎Deprecated: Use read_routing_strategy(RandomReplicaStrategy) instead
pub fn read_from_replicas(self) -> ClusterClientBuilder
Use read_routing_strategy(RandomReplicaStrategy) instead
Enables reading from replicas for all new connections (default is disabled).
Read queries will go to a random replica node and write queries will go to the primary node. If there are no replica nodes, then all queries will go to the primary node.
Sourcepub fn read_routing_strategy(
self,
strategy: impl ReadRoutingStrategyFactory + 'static,
) -> ClusterClientBuilder
pub fn read_routing_strategy( self, strategy: impl ReadRoutingStrategyFactory + 'static, ) -> ClusterClientBuilder
Sets a custom ReadRoutingStrategyFactory for routing read commands within Shards.
Cluster slots are assigned to a shard consisting of a primary node and zero or more replica nodes. By default, the cluster client will route all commands to the primary node of a shard.
By providing a strategy factory here, you can control how read requests will be routed within a shard. This allows the routing of reads to replicas.
The strategy factory is responsible for producing a ReadRoutingStrategy each time
a new connection is created from this client.
A blanket implementation of ReadRoutingStrategyFactory is provided for any
T: ReadRoutingStrategy + Default + 'static, so simple strategies can be passed directly.
The blanket implementation uses default to construct a new strategy for each connection.
The cluster_read_routing module provides built-in simple strategies such as
RandomReplicaStrategy and RoundRobinReplicaStrategy.
You can implement your own ReadRoutingStrategy using the provided traits.
For strategies that need to maintain shared state, such as cross-connection latency tracking,
implement ReadRoutingStrategyFactory directly.
§Examples
use redis::cluster::ClusterClientBuilder;
use redis::cluster_read_routing::{ReadRoutingStrategy, ReadCandidates};
use redis::cluster::NodeAddress;
/// Routes reads to the first replica.
#[derive(Default)]
struct FirstReplica;
impl ReadRoutingStrategy for FirstReplica {
fn route_read<'a>(&self, candidates: &ReadCandidates<'a>) -> &'a NodeAddress {
match candidates {
ReadCandidates::AnyNode(c) => c.replicas().first(),
ReadCandidates::ReplicasOnly(c) => c.replicas().first(),
}
}
}
let client = ClusterClientBuilder::new(vec!["redis://127.0.0.1:6379/"])
.read_routing_strategy(FirstReplica)
.build()
.unwrap();Sourcepub fn connection_timeout(
self,
connection_timeout: Duration,
) -> ClusterClientBuilder
pub fn connection_timeout( self, connection_timeout: Duration, ) -> ClusterClientBuilder
Enables timing out on slow connection time.
If enabled, the cluster will only wait the given time on each connection attempt to each node.
Sourcepub fn response_timeout(
self,
response_timeout: Duration,
) -> ClusterClientBuilder
pub fn response_timeout( self, response_timeout: Duration, ) -> ClusterClientBuilder
Enables timing out on slow responses.
If enabled, the cluster will only wait the given time to each response from each node.
This timeout is also used as the overall response timeout (including retries) unless
overridden with Self::overall_response_timeout.
Sourcepub fn overall_response_timeout(
self,
timeout: Option<Duration>,
) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn overall_response_timeout( self, timeout: Option<Duration>, ) -> ClusterClientBuilder
cluster-async only.Sets the overall timeout for a complete cluster request, including all retries, reconnections, and redirections (e.g. MOVED/ASK).
By default this matches response_timeout, meaning the same duration is used both
per-attempt and overall. This can cause requests to time out when retries are needed,
since the retry must complete within whatever time remains from the original timeout.
Set to None to disable the overall response timeout. Each individual attempt will
still be bounded by response_timeout, but the total operation can take longer when
retries occur. Set to Some(duration) to use a specific overall timeout independent
of response_timeout.
Sourcepub fn use_protocol(self, protocol: ProtocolVersion) -> ClusterClientBuilder
pub fn use_protocol(self, protocol: ProtocolVersion) -> ClusterClientBuilder
Sets the protocol with which the client should communicate with the server.
Sourcepub fn database_id(self, database_id: i64) -> ClusterClientBuilder
pub fn database_id(self, database_id: i64) -> ClusterClientBuilder
Sets the numbered database for the cluster client.
If left unset, the database is inherited from the first
node’s URL (e.g. redis://127.0.0.1:6379/4), in which case all initial
nodes must specify the same database. If set, it must not conflict with a
database carried by any initial node’s URL.
The selected database is reapplied automatically after reconnects.
Note that selecting a non-zero database in cluster mode requires a server that supports multiple databases in cluster mode; otherwise the connection handshake will fail.
Sourcepub fn push_sender(
self,
push_sender: impl AsyncPushSender,
) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn push_sender( self, push_sender: impl AsyncPushSender, ) -> ClusterClientBuilder
cluster-async only.Sets sender sender for push values.
The sender can be a channel, or an arbitrary function that handles crate::PushInfo values. This will fail client creation if the connection isn’t configured for RESP3 communications via the crate::RedisConnectionInfo::set_protocol function.
§Examples
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let config = ClusterClientBuilder::new(vec!["redis://127.0.0.1:6379/"])
.use_protocol(redis::ProtocolVersion::RESP3)
.push_sender(tx);let messages = Arc::new(Mutex::new(Vec::new()));
let config = ClusterClientBuilder::new(vec!["redis://127.0.0.1:6379/"])
.use_protocol(redis::ProtocolVersion::RESP3)
.push_sender(move |msg|{
let Ok(mut messages) = messages.lock() else {
return Err(redis::aio::SendError);
};
messages.push(msg);
Ok(())
});Sourcepub fn tcp_settings(self, tcp_settings: TcpSettings) -> ClusterClientBuilder
pub fn tcp_settings(self, tcp_settings: TcpSettings) -> ClusterClientBuilder
Set the behavior of the underlying TCP connections.
Sourcepub fn node_address_map(
self,
map: HashMap<NodeAddress, NodeAddress>,
) -> ClusterClientBuilder
pub fn node_address_map( self, map: HashMap<NodeAddress, NodeAddress>, ) -> ClusterClientBuilder
Sets a node address map for remapping cluster node addresses.
In TLS-enabled clusters, nodes may advertise IP addresses via CLUSTER SLOTS,
but TLS certificates are issued for domain names. This causes TLS verification
to fail because the certificate’s Subject Alternative Names don’t include
the IP address.
The node address map lets you provide a mapping from the IP-based addresses
returned by CLUSTER SLOTS to the hostnames that match the TLS certificates.
The mapping is applied at connection time only — the internal slot map retains
the original addresses so that MOVED/ASK redirects continue to work.
Sourcepub fn async_dns_resolver(
self,
resolver: impl AsyncDNSResolver,
) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn async_dns_resolver( self, resolver: impl AsyncDNSResolver, ) -> ClusterClientBuilder
cluster-async only.Set asynchronous DNS resolver for the underlying TCP connections.
The parameter resolver must implement the crate::io::AsyncDNSResolver trait.
Sourcepub fn cache_config(self, cache_config: CacheConfig) -> ClusterClientBuilder
Available on crate features cache-aio and cluster-async only.
pub fn cache_config(self, cache_config: CacheConfig) -> ClusterClientBuilder
cache-aio and cluster-async only.Sets cache config for crate::cluster_async::ClusterConnection, check CacheConfig for more details.
Sourcepub fn connection_concurrency_limit(self, limit: usize) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn connection_concurrency_limit(self, limit: usize) -> ClusterClientBuilder
cluster-async only.Sets the maximum number of outstanding requests allowed per connection to a cluster node.
When set, each node connection will allow at most limit concurrent in-flight requests.
Additional requests will wait until an in-flight request completes.
Pipelined commands try to acquire one permit per command, but will proceed with fewer if not all are immediately available. This means a pipeline may temporarily push the effective in-flight count above the limit.
This is useful for preventing a large backlog of commands from building up when a node goes offline or becomes slow. Without a limit, requests continue to queue unboundedly on the connection. When the node is degraded, requests near the back of the queue spend most of their time waiting behind earlier requests and are likely to hit their response timeout before the server even processes them – wasting work on both sides. Setting a concurrency limit caps the number of in-flight requests per node, so backpressure is applied earlier and fewer requests are lost to timeouts.
By default there is no limit.
Sourcepub fn write_backpressure_boundary(
self,
boundary: usize,
) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn write_backpressure_boundary( self, boundary: usize, ) -> ClusterClientBuilder
cluster-async only.Sets the flush threshold (backpressure boundary) for each node connection’s outbound write buffer.
See crate::AsyncConnectionConfig::set_write_backpressure_boundary for full semantics.
This value is applied identically to every node connection in the cluster.
When left unset, connections keep tokio_util’s default boundary.
Sourcepub fn set_credentials_provider<P>(self, provider: P) -> ClusterClientBuilderwhere
P: StreamingCredentialsProvider + 'static,
Available on crate features cluster-async and token-based-authentication only.
pub fn set_credentials_provider<P>(self, provider: P) -> ClusterClientBuilderwhere
P: StreamingCredentialsProvider + 'static,
cluster-async and token-based-authentication only.Sets a credentials provider for dynamic authentication (e.g., token-based authentication) on all cluster node connections.
Each node connection will independently subscribe to the provider and automatically re-authenticate when new credentials are emitted.
Sourcepub fn max_connection_attempts(
self,
max_attempts: NonZero<usize>,
) -> ClusterClientBuilder
Available on crate feature cluster-async only.
pub fn max_connection_attempts( self, max_attempts: NonZero<usize>, ) -> ClusterClientBuilder
cluster-async only.Sets the maximum number of connection attempts to a cluster node before giving up, and removing the node from the cluster. This is useful for clusters with a large number of nodes, where some nodes may be temporarily unavailable. Removed nodes will be re-added to the cluster after a topology refresh. If the value isn’t set, reconnect attempts will continue indefinitely until the node is available again.