Skip to main content

ClusterClientBuilder

Struct ClusterClientBuilder 

Source
pub struct ClusterClientBuilder { /* private fields */ }
Available on crate feature cluster only.
Expand description

Used to configure and build a ClusterClient.

Implementations§

Source§

impl ClusterClientBuilder

Source

pub fn new<T>( initial_nodes: impl IntoIterator<Item = T>, ) -> ClusterClientBuilder

Creates a new ClusterClientBuilder with the provided initial_nodes.

This is the same as ClusterClient::builder(initial_nodes).

Source

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.

Source

pub fn password(self, password: impl AsRef<str>) -> ClusterClientBuilder

Sets password for the new ClusterClient.

Source

pub fn username(self, username: impl AsRef<str>) -> ClusterClientBuilder

Sets username for the new ClusterClient.

Source

pub fn retries(self, retries: u32) -> ClusterClientBuilder

Sets number of retries for the new ClusterClient.

Source

pub fn max_retry_wait(self, max_wait: u64) -> ClusterClientBuilder

Sets maximal wait time in millisceonds between retries for the new ClusterClient.

Source

pub fn min_retry_wait(self, min_wait: u64) -> ClusterClientBuilder

Sets minimal wait time in millisceonds between retries for the new ClusterClient.

Source

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.

Source

pub fn tls(self, tls: TlsMode) -> ClusterClientBuilder

Available on crate features 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.

Source

pub fn danger_accept_invalid_hostnames( self, insecure: bool, ) -> ClusterClientBuilder

Available on crate features 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.

Source

pub fn certs(self, certificates: TlsCertificates) -> ClusterClientBuilder

Available on crate feature 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 - TlsCertificates structure containing:
    • client_tls - Optional ClientTlsConfig containing byte streams for

      • client_cert - client’s byte stream containing client certificate in PEM format
      • client_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.

Source

pub fn read_from_replicas(self) -> ClusterClientBuilder

👎Deprecated:

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.

Source

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();
Source

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.

Source

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.

Source

pub fn overall_response_timeout( self, timeout: Option<Duration>, ) -> ClusterClientBuilder

Available on crate feature 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.

Source

pub fn use_protocol(self, protocol: ProtocolVersion) -> ClusterClientBuilder

Sets the protocol with which the client should communicate with the server.

Source

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.

Source

pub fn push_sender( self, push_sender: impl AsyncPushSender, ) -> ClusterClientBuilder

Available on crate feature 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(())
    });
Source

pub fn tcp_settings(self, tcp_settings: TcpSettings) -> ClusterClientBuilder

Set the behavior of the underlying TCP connections.

Source

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.

Source

pub fn async_dns_resolver( self, resolver: impl AsyncDNSResolver, ) -> ClusterClientBuilder

Available on crate feature cluster-async only.

Set asynchronous DNS resolver for the underlying TCP connections.

The parameter resolver must implement the crate::io::AsyncDNSResolver trait.

Source

pub fn cache_config(self, cache_config: CacheConfig) -> ClusterClientBuilder

Available on crate features cache-aio and cluster-async only.

Sets cache config for crate::cluster_async::ClusterConnection, check CacheConfig for more details.

Source

pub fn connection_concurrency_limit(self, limit: usize) -> ClusterClientBuilder

Available on crate feature 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.

Source

pub fn write_backpressure_boundary( self, boundary: usize, ) -> ClusterClientBuilder

Available on crate feature 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.

Source

pub fn set_credentials_provider<P>(self, provider: P) -> ClusterClientBuilder
where P: StreamingCredentialsProvider + 'static,

Available on crate features 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.

Source

pub fn max_connection_attempts( self, max_attempts: NonZero<usize>, ) -> ClusterClientBuilder

Available on crate feature 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.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more