pub struct ConnectionPool<S> { /* private fields */ }Expand description
A pool of Redis connections that dispatches commands across them.
Generic over S: RedisExecutor, so it works with:
RedisConnection(standalone)ClusterConnection(cluster – each entry manages its own topology)SentinelConnection(sentinel – each entry discovers its own master)ResilientConnection(standalone with auto-reconnect)- Any custom type implementing
RedisExecutor
The pool implements Clone via Arc for cross-task sharing and
implements RedisExecutor itself for composability.
§Concurrency
ConnectionPool<S> is Clone + Send + Sync when S: Send. All clones
share the same pool via Arc. Each individual connection is protected by
its own Mutex, so up to N commands can execute in parallel (one per
pooled connection). The dispatch strategy controls which connection handles
each command.
Implementations§
Source§impl<S> ConnectionPool<S>where
S: Send + 'static,
impl<S> ConnectionPool<S>where
S: Send + 'static,
Sourcepub async fn connect<F, Fut>(
size: usize,
factory: F,
) -> Result<Self, RedisError>
pub async fn connect<F, Fut>( size: usize, factory: F, ) -> Result<Self, RedisError>
Create a pool by calling a factory function size times.
Each call to factory should return a new, independent connection.
For cluster connections, each entry will discover its own topology.
Sourcepub async fn connect_with_config<F, Fut>(
config: PoolConfig,
factory: F,
) -> Result<Self, RedisError>
pub async fn connect_with_config<F, Fut>( config: PoolConfig, factory: F, ) -> Result<Self, RedisError>
Create a pool with custom configuration.
Sourcepub async fn connect_with_factory<Fact>(
config: PoolConfig,
factory: Fact,
) -> Result<Self, RedisError>where
Fact: PoolFactory<Connection = S>,
S: RedisExecutor,
pub async fn connect_with_factory<Fact>(
config: PoolConfig,
factory: Fact,
) -> Result<Self, RedisError>where
Fact: PoolFactory<Connection = S>,
S: RedisExecutor,
Create a pool with custom configuration and a PoolFactory.
The factory is used both to build the initial connections and to replace any connection slot that fails a health-check PING. This ensures that a single dead connection does not permanently degrade pool capacity.
Sourcepub fn connect_lazy<Fact>(config: PoolConfig, factory: Fact) -> Selfwhere
Fact: PoolFactory<Connection = S>,
S: RedisExecutor,
pub fn connect_lazy<Fact>(config: PoolConfig, factory: Fact) -> Selfwhere
Fact: PoolFactory<Connection = S>,
S: RedisExecutor,
Create a factory-backed pool without opening a connection.
The first command creates the first slot; later acquisition contention
grows the pool up to config.max_size (or config.size when omitted).
The lazy pool’s effective minimum is zero, regardless of
config.min_size, so an explicitly spawned idle reaper may return it
to zero while the application is inactive.
Sourcepub fn from_connections(
connections: Vec<S>,
config: PoolConfig,
) -> Result<Self, RedisError>
pub fn from_connections( connections: Vec<S>, config: PoolConfig, ) -> Result<Self, RedisError>
Build a pool from pre-created connections using the given PoolConfig.
Sizing fields are ignored here because a pool without a retained factory cannot restore reaped capacity. The pool is fixed at the number of supplied connections. Dispatch, health-check, acquisition-timeout, name, and metrics settings are applied normally.
§Errors
Returns an error if connections is empty.
Sourcepub fn dispatch_strategy(&self) -> DispatchStrategy
pub fn dispatch_strategy(&self) -> DispatchStrategy
Returns the dispatch strategy.
Sourcepub fn stats(&self) -> PoolStats
pub fn stats(&self) -> PoolStats
Returns a snapshot of current pool utilization.
Reads the per-connection in-flight atomic counters to compute idle and active connection counts. This is a non-blocking, snapshot-in- time read — values may have changed by the time the caller acts on them.
Useful for emitting redis_pool_connections_active /
redis_pool_connections_idle Prometheus metrics.
Sourcepub async fn reap_idle_connections(&self) -> usize
pub async fn reap_idle_connections(&self) -> usize
Remove idle connections above the configured minimum immediately.
This is a one-shot operation and does not spawn a task. It returns zero
when no idle_timeout is configured or no eligible slot exists.
Sourcepub fn spawn_idle_reaper(&self, interval: Duration) -> IdleReaperHandle
pub fn spawn_idle_reaper(&self, interval: Duration) -> IdleReaperHandle
Explicitly spawn periodic idle-connection reaping.
Pool construction never starts this task. The first sweep runs
immediately, then every interval. Dropping the returned handle stops
the task.
§Panics
Panics when interval is zero, no idle timeout is configured, or this
method is called outside a Tokio runtime.
Sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
Returns true once close has been called on this pool
or any of its clones.
Sourcepub async fn close(self)
pub async fn close(self)
Gracefully close the pool, draining in-flight commands.
Flips a shared “closed” bit so that every clone of this pool rejects new
commands with RedisError::ConnectionClosed, then waits for all
in-flight commands to finish before returning. Each accepted command
atomically increments a pool-wide operation count while confirming the
pool is open, so closing and admission have one unambiguous order.
This is the SIGTERM drain path: stop accepting work, let outstanding commands complete, then exit. It does not itself close the underlying connections – dropping the pool (and its last clone) releases them – but it guarantees no command is mid-flight when the connections are dropped.
Because the state is shared through the pool’s Arc, calling close on
one clone drains and closes the pool seen by every clone. Commands
admitted before the close transition finish normally; commands racing
after it are rejected.
§Example
use redis_tower::{ConnectionPool, RedisConnection};
let pool =
ConnectionPool::connect(4, || RedisConnection::connect("127.0.0.1:6379")).await?;
// On shutdown (SIGTERM, ctrl-c, ...): stop accepting new work and drain
// the pool before exit.
pool.close().await;Source§impl<S> ConnectionPool<S>where
S: RedisExecutor + Send + 'static,
impl<S> ConnectionPool<S>where
S: RedisExecutor + Send + 'static,
Sourcepub fn spawn_health_prober(
&self,
config: HealthProberConfig,
) -> HealthProberHandle
pub fn spawn_health_prober( &self, config: HealthProberConfig, ) -> HealthProberHandle
Explicitly spawn active PING probing with an owned lifecycle handle.
Pool construction never starts a prober. The first sweep runs immediately. Dropping the returned handle stops the task.
Sourcepub fn spawn_health_prober_with<P>(
&self,
config: HealthProberConfig,
probe: P,
) -> HealthProberHandlewhere
P: HealthProbe<S>,
pub fn spawn_health_prober_with<P>(
&self,
config: HealthProberConfig,
probe: P,
) -> HealthProberHandlewhere
P: HealthProbe<S>,
Explicitly spawn active probing with a custom HealthProbe.
Results are observational: they update PoolStats and
MetricsRecorder without silently changing dispatch policy.
§Panics
Panics when the interval or timeout is zero, or when called outside a Tokio runtime.
Source§impl ConnectionPool<RedisConnection>
impl ConnectionPool<RedisConnection>
Sourcepub async fn reauthenticate_all(
&self,
credentials: &Credentials,
) -> Result<(), RedisError>
pub async fn reauthenticate_all( &self, credentials: &Credentials, ) -> Result<(), RedisError>
Send AUTH with credentials to every active pool connection.
Slots are locked one at a time, so a credential update never races a command on the same socket. Other slots remain available while the update progresses. A connection created concurrently through a provider-backed factory fetches the provider’s current credentials and therefore does not need to be revisited by this pass.
If a slot rejects the replacement, this method returns the first error
after attempting every active slot but leaves failed slots installed
with their previous Redis identity. Call Self::close and rebuild the
pool through its provider-backed factory when rotation must fail closed.
Sourcepub fn spawn_credential_reauthentication(
&self,
provider: Arc<dyn StreamingCredentialProvider>,
) -> CredentialReauthenticationHandle
pub fn spawn_credential_reauthentication( &self, provider: Arc<dyn StreamingCredentialProvider>, ) -> CredentialReauthenticationHandle
Apply every credential emitted by provider to all active slots.
Dropping the returned handle stops future updates without closing the
pool. Use the same provider in the pool’s
CredentialConnectionFactory so
replacement and newly grown slots authenticate with current material.
Rejected updates are logged without their error text and later updates
are still consumed; failed slots are not automatically removed. A
fail-closed owner must close and rebuild the pool before routing more
application traffic.
Source§impl<S> ConnectionPool<S>where
S: RedisExecutor + Send + 'static,
impl<S> ConnectionPool<S>where
S: RedisExecutor + Send + 'static,
Sourcepub async fn execute<Cmd: Command>(
&self,
cmd: Cmd,
) -> Result<Cmd::Response, RedisError>
pub async fn execute<Cmd: Command>( &self, cmd: Cmd, ) -> Result<Cmd::Response, RedisError>
Execute a command through the pool.
This is the primary API. The pool selects a connection via the
configured dispatch strategy and executes the command on it. To avoid
head-of-line blocking, if the strategy-selected connection is currently
busy the pool first scans for any idle connection (via try_lock) and
uses that instead, only awaiting a busy slot when every connection is in
use.
If health_check_interval is configured and the selected connection
has been idle longer than the interval, a PING is sent first to
verify the connection is alive. If the PING fails and the pool was
built with a PoolFactory (via ConnectionPool::connect_with_factory),
the dead slot is replaced with a fresh connection before the actual
command is executed. If no factory is available, the PING error is
returned to the caller.
If cmd is wrapped in redis_tower_core::WithDeadline, pool
acquisition observes that same absolute deadline. The request deadline
and PoolConfig::acquisition_timeout do not add together: whichever
expires first determines the error.
Sourcepub async fn health_check(&self) -> Result<(), RedisError>
pub async fn health_check(&self) -> Result<(), RedisError>
Send a PING to every connection in the pool.
Acquires each connection sequentially and sends PING. Returns
Ok(()) if all connections respond successfully. Returns the first
error encountered if any connection is unhealthy.
Useful for Kubernetes readiness probes and /health endpoints. For
a fast single-connection liveness check, call
execute with Ping
directly.