pub struct RedisConnection { /* private fields */ }Expand description
A single Redis connection implementing tower::Service<Cmd>.
This is the foundational building block. It owns a framed TCP/TLS/Unix connection and serializes commands one at a time.
RedisConnection requires &mut self for Service::call, which is the
correct Tower contract for a non-multiplexed connection. For shared access
across tasks, wrap with tower::buffer::Buffer.
Cancelling an in-flight Service::call closes the connection. Once a
request may have reached Redis, reusing its transport could let the next
call consume the cancelled request’s late response. A subsequent
poll_ready therefore returns RedisError::ConnectionClosed.
§Example
Typed command types such as Get live in the redis-tower-commands crate,
which depends on this one, so the example below stands in a minimal local
Command implementation (hidden) and runs it with
execute:
use redis_tower_core::{Command, Frame, RedisConnection, RedisError};
let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
let value = conn.execute(Get("my_key".to_string())).await?;Implementations§
Source§impl RedisConnection
impl RedisConnection
Sourcepub async fn connect(addr: &str) -> Result<RedisConnection, RedisError>
pub async fn connect(addr: &str) -> Result<RedisConnection, RedisError>
Connect to a Redis server over TCP.
TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s
interval, 3 probes. Use connect_with_keepalive
to supply custom keepalive parameters.
Sourcepub async fn connect_with_config(
addr: &str,
config: &ConnectionConfig,
) -> Result<RedisConnection, RedisError>
pub async fn connect_with_config( addr: &str, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>
Connect to a Redis server over TCP with explicit connection settings.
The configured RESP decode limits are installed before any server data
is read, including CLIENT SETINFO and protocol-negotiation replies.
Sourcepub async fn connect_with_keepalive(
addr: &str,
keepalive: &KeepaliveConfig,
) -> Result<RedisConnection, RedisError>
pub async fn connect_with_keepalive( addr: &str, keepalive: &KeepaliveConfig, ) -> Result<RedisConnection, RedisError>
Connect to a Redis server over TCP with a custom keepalive configuration.
§Errors
Returns RedisError::Connection if the TCP connection fails or if
the keepalive socket options cannot be applied.
Sourcepub async fn connect_with_timeout(
addr: &str,
timeout: Duration,
) -> Result<RedisConnection, RedisError>
pub async fn connect_with_timeout( addr: &str, timeout: Duration, ) -> Result<RedisConnection, RedisError>
Connect to a Redis server over TCP with a connect timeout.
If the TCP handshake is not completed within timeout, returns
RedisError::ConnectTimeout instead of waiting for the OS-default
timeout (which can be several minutes on unreachable hosts).
TCP keepalive is enabled with sensible defaults after the connection is
established. Use connect_with_config to
combine a timeout with custom keepalive or RESP decode limits.
§Example
use redis_tower_core::RedisConnection;
use std::time::Duration;
let conn = RedisConnection::connect_with_timeout("127.0.0.1:6379", Duration::from_secs(3)).await;Sourcepub async fn connect_tls(
addr: &str,
hostname: &str,
tls_config: &TlsConfig,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_tls( addr: &str, hostname: &str, tls_config: &TlsConfig, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect over TLS using the provided configuration.
Requires either the tls-native-tls or tls-rustls feature.
TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s
interval, 3 probes. Use connect_tls_with_keepalive
to supply custom keepalive parameters.
Sourcepub async fn connect_tls_with_config(
addr: &str,
hostname: &str,
tls_config: &TlsConfig,
config: &ConnectionConfig,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_tls_with_config( addr: &str, hostname: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect over TLS with explicit connection settings.
The TCP connect timeout, keepalive policy, protocol negotiation, and
RESP decode limits all come from config. The connect timeout covers
the TCP handshake only, matching connect_tls_with_timeout.
Sourcepub async fn connect_tls_with_keepalive(
addr: &str,
hostname: &str,
tls_config: &TlsConfig,
keepalive: &KeepaliveConfig,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_tls_with_keepalive( addr: &str, hostname: &str, tls_config: &TlsConfig, keepalive: &KeepaliveConfig, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect over TLS with a custom keepalive configuration.
Requires either the tls-native-tls or tls-rustls feature.
§Errors
Returns RedisError::Connection if the TCP connection or TLS
handshake fails, or if the keepalive socket options cannot be applied.
Sourcepub async fn connect_tls_with_timeout(
addr: &str,
hostname: &str,
tls_config: &TlsConfig,
timeout: Duration,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_tls_with_timeout( addr: &str, hostname: &str, tls_config: &TlsConfig, timeout: Duration, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect over TLS with a connect timeout.
Requires either the tls-native-tls or tls-rustls feature.
If the TCP handshake is not completed within timeout, returns
RedisError::ConnectTimeout. The timeout covers only the TCP
connection phase; the TLS handshake runs outside the timeout window.
§Errors
Returns RedisError::ConnectTimeout if the TCP connect times out,
RedisError::Connection if the TCP connection or TLS handshake
fails, or RedisError::Connection if keepalive socket options
cannot be applied.
Sourcepub async fn connect_url(url: &str) -> Result<RedisConnection, RedisError>
pub async fn connect_url(url: &str) -> Result<RedisConnection, RedisError>
Connect using a Redis URL.
Supports redis://, rediss:// (TLS), their Valkey aliases, and
unix://, redis+unix://, and valkey+unix:// Unix-socket URLs.
Unix URLs accept user, pass, db, and protocol query parameters:
redis+unix:///run/redis%20server.sock?user=app&pass=secret&db=1&protocol=resp3For rediss:// URLs, a TLS backend feature must be enabled.
The tls-rustls backend is preferred if both are enabled.
Sourcepub async fn connect_url_with_config(
url: &str,
config: &ConnectionConfig,
) -> Result<RedisConnection, RedisError>
pub async fn connect_url_with_config( url: &str, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>
Connect using a Redis URL with explicit connection settings.
URL authentication and database selection run before RESP negotiation.
?protocol=2|resp2|3|resp3 selects a protocol when the connection
config uses ProtocolVersion::Auto. An explicit protocol in
ConnectionConfig takes precedence, which lets RESP3-only clients
enforce their invariant. Decode limits are active for every setup
response.
Sourcepub async fn begin_url_connection_with_config(
url: &str,
config: &ConnectionConfig,
) -> Result<PendingRedisConnection, RedisError>
pub async fn begin_url_connection_with_config( url: &str, config: &ConnectionConfig, ) -> Result<PendingRedisConnection, RedisError>
Open the transport described by a Redis URL without applying its static credentials, selected database, or RESP protocol yet.
This is the provider-authentication seam used by higher-level
connection factories. The returned connection starts in RESP2, while
preserving the URL’s TCP, TLS, or Unix transport, database, and
protocol settings. Authenticate it through
PendingRedisConnection::connection_mut, then call
PendingRedisConnection::finish.
The URL’s username and password are intentionally ignored on this path;
they remain active on connect_url_with_config.
Sourcepub async fn connect_url_with_tls(
url: &str,
tls_config: &TlsConfig,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_url_with_tls( url: &str, tls_config: &TlsConfig, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect from a Redis URL, performing the TLS handshake with an explicit
TlsConfig.
Like connect_url but the caller supplies the TLS
configuration – a custom root CA, a client certificate for mTLS, or a
pre-built backend – instead of the URL’s hardcoded default. The host,
port, and any AUTH/SELECT parameters still come from the URL, and the
connection always uses TLS (for either a redis:// or rediss:// URL).
Unix-socket URLs are rejected.
§Example
use redis_tower_core::RedisConnection;
use redis_tower_core::tls::TlsConfig;
let tls = TlsConfig::default_rustls()
.with_root_ca_pem(std::fs::read("ca.pem")?)
.with_client_auth_pem(std::fs::read("client.pem")?, std::fs::read("client.key")?);
let conn = RedisConnection::connect_url_with_tls(
"rediss://default:secret@redis.internal:6379",
&tls,
)
.await?;Sourcepub async fn connect_url_with_tls_and_config(
url: &str,
tls_config: &TlsConfig,
config: &ConnectionConfig,
) -> Result<RedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn connect_url_with_tls_and_config( url: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>
tls-native-tls or tls-rustls only.Connect from a Redis URL with explicit TLS and connection settings.
This combines a custom CA or mTLS configuration with keepalive, connection timeout, protocol, and RESP decode-limit settings. Unix socket URLs are rejected because this connector always uses TLS.
Sourcepub async fn begin_url_connection_with_tls_and_config(
url: &str,
tls_config: &TlsConfig,
config: &ConnectionConfig,
) -> Result<PendingRedisConnection, RedisError>
Available on crate features tls-native-tls or tls-rustls only.
pub async fn begin_url_connection_with_tls_and_config( url: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<PendingRedisConnection, RedisError>
tls-native-tls or tls-rustls only.Open a staged URL connection using explicit TLS configuration.
This is the custom-CA/mTLS counterpart to
begin_url_connection_with_config.
The URL must describe a TCP endpoint; Unix URLs are rejected. Static
URL credentials are ignored so the caller can authenticate through a
dynamic provider before database selection and protocol negotiation.
Sourcepub async fn connect_resp3(addr: &str) -> Result<RedisConnection, RedisError>
pub async fn connect_resp3(addr: &str) -> Result<RedisConnection, RedisError>
Connect to a Redis server and negotiate RESP3 protocol.
Sends HELLO 3 after connecting. The server will respond with
RESP3 frames for all subsequent commands.
Sourcepub fn is_resp3(&self) -> bool
pub fn is_resp3(&self) -> bool
Whether this connection has negotiated RESP3 (via HELLO 3).
Returns false for a plain RESP2 connection. Useful for tests and for
middleware that behaves differently under the two protocols – push-based
features such as client-side caching require RESP3.
Sourcepub async fn connect_with_protocol(
addr: &str,
version: ProtocolVersion,
) -> Result<RedisConnection, RedisError>
pub async fn connect_with_protocol( addr: &str, version: ProtocolVersion, ) -> Result<RedisConnection, RedisError>
Connect and negotiate the protocol explicitly.
ProtocolVersion::AutotriesHELLO 3and silently falls back to RESP2 on servers that do not support it (Redis < 6.0).ProtocolVersion::Resp3forces RESP3 and errors if it is rejected.ProtocolVersion::Resp2stays on RESP2 without sendingHELLO.
§Example
use redis_tower_core::{RedisConnection, ProtocolVersion};
let conn = RedisConnection::connect_with_protocol(
"127.0.0.1:6379",
ProtocolVersion::Resp3,
).await?;
assert!(conn.is_resp3());Sourcepub async fn negotiate_protocol(
&mut self,
version: ProtocolVersion,
) -> Result<(), RedisError>
pub async fn negotiate_protocol( &mut self, version: ProtocolVersion, ) -> Result<(), RedisError>
Negotiate version on an already-connected connection.
This is useful for connection setup that must run before protocol
negotiation, such as authenticating a protected Redis Cluster node.
Requesting RESP2 only sends HELLO 2 when the connection is currently
in RESP3; a fresh RESP2 connection does not pay an extra round trip.
Sourcepub async fn hello(&mut self, version: u8) -> Result<Frame, RedisError>
pub async fn hello(&mut self, version: u8) -> Result<Frame, RedisError>
Send HELLO to negotiate protocol version.
HELLO 3 switches to RESP3, HELLO 2 switches back to RESP2.
Sourcepub fn from_stream(stream: RedisStream) -> RedisConnection
pub fn from_stream(stream: RedisStream) -> RedisConnection
Wrap an existing stream in a RedisConnection.
Sourcepub fn from_stream_with_config(
stream: RedisStream,
config: &ConnectionConfig,
) -> RedisConnection
pub fn from_stream_with_config( stream: RedisStream, config: &ConnectionConfig, ) -> RedisConnection
Wrap an existing stream using explicit connection settings.
Only the RESP decode limits apply to an already-open stream. Keepalive, connect timeout, and protocol negotiation are connection-establishment settings and are not replayed by this synchronous constructor.
Sourcepub fn subscribe_pushes(&mut self) -> UnboundedReceiver<Frame>
pub fn subscribe_pushes(&mut self) -> UnboundedReceiver<Frame>
Subscribe to RESP3 push messages.
Returns a receiver for out-of-band push frames (e.g., invalidation messages from CLIENT TRACKING). Push frames received during normal command execution are automatically routed to this channel.
If nobody subscribes, push frames are silently discarded.
§Reconnection Warning
Push subscriptions do not survive reconnection. If the underlying
TCP connection drops and a new connection is established (e.g., via
ResilientConnection or manual
reconnection), any server-side state such as CLIENT TRACKING
registrations is lost. The push receiver will stop receiving
messages until the tracking is re-enabled on the new connection.
To handle this, implement ConnectionFactory
yourself and replay setup commands (e.g., CLIENT TRACKING ON) inside
connect(). This ensures the setup runs on every fresh connection,
including reconnections.
ConnectionFactory lives in the redis-tower crate, which depends on
this one, so the setup below is shown as the standalone function that
the factory’s connect() body calls:
use redis_tower_core::{Frame, RedisConnection, RedisError};
use redis_tower_protocol::helpers::{array, bulk};
use tokio::sync::mpsc::UnboundedReceiver;
let mut conn = RedisConnection::connect_resp3(addr).await?;
// Replay CLIENT TRACKING and re-subscribe on every new connection.
conn.execute_pipeline(vec![array(vec![bulk("CLIENT"), bulk("TRACKING"), bulk("ON")])])
.await?;
let pushes = conn.subscribe_pushes();
Ok((conn, pushes))Sourcepub async fn read_idle_push(&mut self) -> Result<(), RedisError>
pub async fn read_idle_push(&mut self) -> Result<(), RedisError>
Wait for one unsolicited RESP3 push frame while the connection is idle.
The frame is routed to the receiver returned by subscribe_pushes,
matching the behavior of command-response reads. EOF, decode failures,
and non-push frames are returned as errors because a response arriving
without an outstanding command means protocol alignment has been lost.
This method is cancellation-safe: it borrows the framed transport in
place, so cancelling the wait preserves both the transport and any
partially buffered frame. It is intended for an exclusive connection
owner, such as an auto-pipeline worker, and must not be called while a
Service::call future is in flight.
Sourcepub async fn execute<Cmd>(
&mut self,
cmd: Cmd,
) -> Result<<Cmd as Command>::Response, RedisError>where
Cmd: Command,
pub async fn execute<Cmd>(
&mut self,
cmd: Cmd,
) -> Result<<Cmd as Command>::Response, RedisError>where
Cmd: Command,
Send a command and receive the response.
This is the low-level method. Prefer using the Service trait via
tower::ServiceExt::oneshot or Service::call.
§Large values
For values approaching 10MB or larger, the sequential send-then-read
pattern can cause TCP backpressure issues on some managed Redis
services (e.g., ElastiCache) if the write buffer fills before the
response starts being read. Consider using AutoPipelineService
for large-value workloads, or splitting large values across
multiple keys.
Cancelling this future after dispatch closes the connection. The
transport is checked out of self until a complete response has been
read, preventing a later command from consuming a cancelled command’s
response.
Sourcepub async fn execute_pipeline(
&mut self,
frames: Vec<Frame>,
) -> Result<Vec<Frame>, RedisError>
pub async fn execute_pipeline( &mut self, frames: Vec<Frame>, ) -> Result<Vec<Frame>, RedisError>
Send multiple command frames and read all responses in a single roundtrip.
Used by pipeline and transaction implementations. Cancelling before every response has been read closes the connection.
Sourcepub async fn execute_transaction(
&mut self,
watch_frames: Vec<Frame>,
command_frames: Vec<Frame>,
) -> Result<Option<Vec<Frame>>, RedisError>
pub async fn execute_transaction( &mut self, watch_frames: Vec<Frame>, command_frames: Vec<Frame>, ) -> Result<Option<Vec<Frame>>, RedisError>
Execute a WATCH/MULTI/EXEC transaction sequence.
Returns Ok(Some(responses)) on commit, Ok(None) if aborted by WATCH.
Sourcepub fn into_framed(self) -> Result<Framed<RedisStream, RespCodec>, RedisError>
pub fn into_framed(self) -> Result<Framed<RedisStream, RespCodec>, RedisError>
Consume this connection and extract the underlying framed stream.
Fails if a Service::call future is still in flight.
Trait Implementations§
Source§impl PipelineExecutor for RedisConnection
impl PipelineExecutor for RedisConnection
Source§impl RedisExecutor for RedisConnection
impl RedisExecutor for RedisConnection
Source§impl<Cmd> Service<Cmd> for RedisConnectionwhere
Cmd: Command,
impl<Cmd> Service<Cmd> for RedisConnectionwhere
Cmd: Command,
Source§type Error = RedisError
type Error = RedisError
Source§type Future = Pin<Box<dyn Future<Output = Result<<Cmd as Command>::Response, RedisError>> + Send>>
type Future = Pin<Box<dyn Future<Output = Result<<Cmd as Command>::Response, RedisError>> + Send>>
Source§impl TransactionExecutor for RedisConnection
impl TransactionExecutor for RedisConnection
Source§fn execute_transaction(
&mut self,
watch_frames: Vec<Frame>,
command_frames: Vec<Frame>,
) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send
fn execute_transaction( &mut self, watch_frames: Vec<Frame>, command_frames: Vec<Frame>, ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send
Source§const SUPPORTS_TRANSACTION_RETRY: bool = true
const SUPPORTS_TRANSACTION_RETRY: bool = true
transaction and transaction_with_retries. Read moreSource§fn validate_transaction_retry(&self) -> Result<(), RedisError>
fn validate_transaction_retry(&self) -> Result<(), RedisError>
Auto Trait Implementations§
impl !Freeze for RedisConnection
impl !RefUnwindSafe for RedisConnection
impl !UnwindSafe for RedisConnection
impl Send for RedisConnection
impl Sync for RedisConnection
impl Unpin for RedisConnection
impl UnsafeUnpin for RedisConnection
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T, Request> ServiceExt<Request> for T
impl<T, Request> ServiceExt<Request> for T
Source§fn ready(&mut self) -> Ready<'_, Self, Request> ⓘwhere
Self: Sized,
fn ready(&mut self) -> Ready<'_, Self, Request> ⓘwhere
Self: Sized,
Source§fn ready_oneshot(self) -> ReadyOneshot<Self, Request> ⓘwhere
Self: Sized,
fn ready_oneshot(self) -> ReadyOneshot<Self, Request> ⓘwhere
Self: Sized,
Source§fn oneshot(self, req: Request) -> Oneshot<Self, Request> ⓘwhere
Self: Sized,
fn oneshot(self, req: Request) -> Oneshot<Self, Request> ⓘwhere
Self: Sized,
Service, calling it with the provided request once it is ready.Source§fn and_then<F>(self, f: F) -> AndThen<Self, F>
fn and_then<F>(self, f: F) -> AndThen<Self, F>
poll_ready method. Read moreSource§fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
poll_ready method. Read moreSource§fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
poll_ready method. Read moreSource§fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
Result<Self::Response, Self::Error>)
to a different value, regardless of whether the future succeeds or
fails. Read more