### Basic Redis Connection Pool Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Demonstrates creating a Redis connection pool using a URL and performing basic SET and GET operations. Ensure the REDIS__URL environment variable is set. ```rust use std::env; use deadpool_redis::{redis::{cmd, FromRedisValue}, Config, Runtime}; #[tokio::main] async fn main() { let mut cfg = Config::from_url(env::var("REDIS__URL").unwrap()); let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap(); { let mut conn = pool.get().await.unwrap(); cmd("SET") .arg(&["deadpool/test_key", "42"]) .query_async::<()>(&mut conn) .await.unwrap(); } { let mut conn = pool.get().await.unwrap(); let value: String = cmd("GET") .arg(&["deadpool/test_key"]) .query_async(&mut conn) .await.unwrap(); assert_eq!(value, "42".to_string()); } } ``` -------------------------------- ### Config from Environment Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Config.html Example of how to deserialize Config from environment variables using the `config` crate and `serde` feature. ```APIDOC ## §Example (from environment) By enabling the `serde` feature you can read the configuration using the `config` crate as following: ``` REDIS__URL=redis.example.com REDIS__POOL__MAX_SIZE=16 REDIS__POOL__TIMEOUTS__WAIT__SECS=2 REDIS__POOL__TIMEOUTS__WAIT__NANOS=0 ``` ```rust #[derive(serde::Deserialize)] struct Config { redis: deadpool_redis::Config, } impl Config { pub fn from_env() -> Result { let mut cfg = config::Config::builder() .add_source(config::Environment::default().separator("__")) .build()?; cfg.try_deserialize() } } ``` ``` -------------------------------- ### Environment Configuration Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Config.html Example of environment variables for configuring deadpool_redis cluster using the `config` crate. Ensure the `serde` feature is enabled. ```env REDIS_CLUSTER__URLS=redis://127.0.0.1:7000,redis://127.0.0.1:7001 REDIS_CLUSTER__READ_FROM_REPLICAS=true REDIS_CLUSTER__POOL__MAX_SIZE=16 REDIS_CLUSTER__POOL__TIMEOUTS__WAIT__SECS=2 REDIS_CLUSTER__POOL__TIMEOUTS__WAIT__NANOS=0 ``` -------------------------------- ### Example: Periodic Pool Cleanup Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/type.Pool.html This example demonstrates how to periodically clean up the pool by removing connections that haven't been used recently. It spawns a background task that checks connections every 30 seconds and removes those unused for over a minute. ```rust let interval = Duration::from_secs(30); let max_age = Duration::from_secs(60); tokio::spawn(async move { loop { tokio::time::sleep(interval).await; pool.retain(|_, metrics| metrics.last_used() < max_age); } }); ``` -------------------------------- ### Get Ex Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterConnection.html Get the value of a key and set expiration. ```APIDOC ## fn get_ex<'a, K>( &'a mut self, key: K, expire_at: Expiry, ) -> Pin, RedisError>> + Send + 'a>> where K: ToSingleRedisArg + Send + Sync + 'a, Get the value of a key and set expiration Redis Docs ``` -------------------------------- ### hgetall Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets all the fields and values in a hash. ```APIDOC ## hgetall ### Description Retrieves all the field-value pairs stored within a hash. ### Method `hgetall` ### Parameters - `key`: The key of the hash. ### Returns A future that resolves to a map of fields and values or a RedisError. ``` -------------------------------- ### get Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the value of a key. If key is a vec this becomes an `MGET`. ```APIDOC ## get ### Description Get the value of a key. If key is a vec this becomes an `MGET` (if using `TypedCommands`, you should specifically use `mget` to get the correct return type. ### Method `fn get<'a, K, RV>(&'a mut self, key: K) -> Pin> + Send + 'a>>` ### Parameters #### Path Parameters - `key` (K: ToSingleRedisArg + Send + Sync + 'a) - Required - The key to retrieve the value from. ### Response #### Success Response (200) - `Pin> + Send + 'a>>` - A future that resolves to the value of the key. ``` -------------------------------- ### Hkeys Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets all the keys in a hash. ```APIDOC ## hkeys ### Description Gets all the keys in a hash. ### Method `hkeys` ### Parameters - `key`: The key of the hash. ### Returns A future that resolves to a list of all keys in the hash. ``` -------------------------------- ### get_ex Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Get the value of a key and set expiration. ```APIDOC ## get_ex ### Description Get the value of a key and set its expiration time. ### Method `get_ex` ### Parameters #### Path Parameters - **key** (K) - Required - The key whose value is to be retrieved and expiration set. - **expire_at** (Expiry) - Required - The expiration time to set for the key. ### Response #### Success Response (Result) - **RV** - The value of the key. #### Error Response (RedisError) - **RedisError** - An error that occurred during the operation. ``` -------------------------------- ### Config Example from Environment Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Config.html Demonstrates how to configure deadpool-redis cluster settings using environment variables, leveraging the `serde` feature. ```APIDOC ## §Example (from environment) By enabling the `serde` feature you can read the configuration using the `config` crate as following: ``` REDIS_CLUSTER__URLS=redis://127.0.0.1:7000,redis://127.0.0.1:7001 REDIS_CLUSTER__READ_FROM_REPLICAS=true REDIS_CLUSTER__POOL__MAX_SIZE=16 REDIS_CLUSTER__POOL__TIMEOUTS__WAIT__SECS=2 REDIS_CLUSTER__POOL__TIMEOUTS__WAIT__NANOS=0 ``` ```rust #[derive(serde::Deserialize)] struct Config { redis_cluster: deadpool_redis::cluster::Config, } impl Config { pub fn from_env() -> Result { let mut cfg = config::Config::builder() .add_source( config::Environment::default() .separator("__") .try_parsing(true) .list_separator(","), ) .build()?; cfg.try_deserialize() } } ``` ``` -------------------------------- ### Get Del Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterConnection.html Get the value of a key and delete it. ```APIDOC ## fn get_del<'a, K>( &'a mut self, key: K, ) -> Pin, RedisError>> + Send + 'a>> where K: ToSingleRedisArg + Send + Sync + 'a, Get the value of a key and delete it Redis Docs ``` -------------------------------- ### Get and Delete Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the value of a key and then delete it. ```APIDOC ## get_del ### Description Get the value of a key and delete it. ### Method `get_del` ### Parameters - `key`: The key whose value to retrieve and delete. ### Returns A future that resolves to an `Option` containing the key's value if it existed, or a `RedisError`. ``` -------------------------------- ### Get and Delete Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the value of a key and delete it. ```APIDOC ## get_del ### Description Get the value of a key and delete it. ### Method `get_del` ### Parameters - `key`: The key whose value to retrieve and delete. ``` -------------------------------- ### Subscribe and Unsubscribe Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Demonstrates how to subscribe to channels and unsubscribe using RESP3 protocol. Requires a push sender to be configured in the ClusterClientBuilder. Subscription is automatically re-established after disconnections. ```rust let nodes = vec!["redis://127.0.0.1/protocol=3"]; let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let client = redis::cluster::ClusterClientBuilder::new(nodes) .use_protocol(redis::ProtocolVersion::RESP3) .push_sender(tx).build()?; let mut con = client.get_async_connection().await?; con.subscribe(&["channel_1", "channel_2"]).await?; con.unsubscribe(&["channel_1", "channel_2"]).await?; ``` -------------------------------- ### Get and Expire Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the value of a key and set its expiration. ```APIDOC ## get_ex ### Description Get the value of a key and set expiration. ### Method `get_ex` ### Parameters - `key`: The key whose value to retrieve and set expiration for. - `expire_at`: The expiration configuration. ### Returns A future that resolves to an `Option` containing the key's value if it exists, or a `RedisError`. ``` -------------------------------- ### Redis Cluster Connection Pool Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Demonstrates setting up a connection pool for a Redis Cluster using a comma-separated list of URLs from the REDIS_CLUSTER__URLS environment variable. Requires the 'cluster' feature. ```rust use std::env; use deadpool_redis::{redis::{cmd, FromRedisValue}}; use deadpool_redis::cluster::{Config, Runtime}; #[tokio::main] async fn main() { let redis_urls = env::var("REDIS_CLUSTER__URLS") .unwrap() .split(',') .map(String::from) .collect::>(); let mut cfg = Config::from_urls(redis_urls); let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap(); { let mut conn = pool.get().await.unwrap(); cmd("SET") .arg(&["deadpool/test_key", "42"]) .query_async::<()>(&mut conn) .await.unwrap(); } { let mut conn = pool.get().await.unwrap(); let value: String = cmd("GET") .arg(&["deadpool/test_key"]) .query_async(&mut conn) .await.unwrap(); assert_eq!(value, "42".to_string()); } } ``` -------------------------------- ### Get Commands Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Commands for retrieving values associated with keys in Redis. ```APIDOC ## get ### Description Get the value of a key. ### Method `get` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (K) - Required - The key to retrieve. ### Request Example ```rust connection.get(key).await?; ``` ### Response #### Success Response (200) Returns `Option` containing the value if the key exists, otherwise `None`. #### Response Example ```rust Ok(Some("value")) ``` ``` ```APIDOC ## mget ### Description Get values of multiple keys. ### Method `mget` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (K) - Required - A collection of keys to retrieve. ### Request Example ```rust connection.mget(&[key1, key2]).await?; ``` ### Response #### Success Response (200) Returns `Vec>` containing the values for each key. #### Response Example ```rust Ok(vec![Some("value1"), None]) ``` ``` ```APIDOC ## keys ### Description Gets all keys matching a pattern. ### Method `keys` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (K) - Required - The pattern to match keys against. ### Request Example ```rust connection.keys("user:*").await?; ``` ### Response #### Success Response (200) Returns `Vec` containing all matching keys. #### Response Example ```rust Ok(vec!["user:1", "user:2"]) ``` ``` ```APIDOC ## getset ### Description Set the string value of a key and return its old value. ### Method `getset` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (K) - Required - The key to set. - **value** (V) - Required - The new value to set. ### Request Example ```rust connection.getset(key, value).await?; ``` ### Response #### Success Response (200) Returns `Option` containing the old value if the key existed, otherwise `None`. #### Response Example ```rust Ok(Some("old_value")) ``` ``` ```APIDOC ## getrange ### Description Get a range of bytes/substring from the value of a key. Negative values provide an offset from the end of the value. ### Method `getrange` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (K) - Required - The key to retrieve the range from. - **from** (isize) - Required - The starting offset. - **to** (isize) - Required - The ending offset. ### Request Example ```rust connection.getrange(key, 0, 5).await?; ``` ### Response #### Success Response (200) Returns `String` containing the specified range of the value. Returns an empty string if the key doesn’t exist. #### Response Example ```rust Ok("substring") ``` ``` -------------------------------- ### from_connection_info Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/config.rs.html Creates a `Config` instance initialized with `ConnectionInfo`. ```APIDOC ## from_connection_info ### Description Creates a new [`Config`] from the given Redis `ConnectionInfo` structure. ### Signature ```rust #[must_use] pub fn from_connection_info>(connection_info: T) -> Config ``` ### Parameters - `connection_info` (T): A value that can be converted into a `ConnectionInfo`. ``` -------------------------------- ### Hash Get Field Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets a single field from a hash. ```APIDOC ## hget ### Description Gets a single field from a hash. ### Method `hget` ### Parameters - `key`: The key of the hash. - `field`: The field to retrieve from the hash. ``` -------------------------------- ### Get with Expiration Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the value of a key and set expiration. ```APIDOC ## get_ex ### Description Get the value of a key and set expiration. ### Method `get_ex` ### Parameters - `key`: The key whose value to retrieve and set expiration for. - `expire_at`: The expiration configuration. ``` -------------------------------- ### PSubscribe and PUnsubscribe Example Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Shows how to subscribe to channels using patterns and unsubscribe. This functionality requires RESP3 protocol and a push sender. Automatic resubscription occurs after disconnections. ```rust let nodes = vec!["redis://127.0.0.1/protocol=3"]; let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let client = redis::cluster::ClusterClientBuilder::new(nodes) .use_protocol(redis::ProtocolVersion::RESP3) .push_sender(tx).build()?; let mut connection = client.get_async_connection().await?; connection.psubscribe("channel*_1").await?; connection.psubscribe(&["channel*_2", "channel*_3"]).await?; ``` -------------------------------- ### Get Int Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Get a value from Redis and convert it to an Option. ```APIDOC ## fn get_int<'a, K>( &'a mut self, key: K, ) where K: ToSingleRedisArg + Send + Sync + 'a, Get a value from Redis and convert it to an `Option`. ``` -------------------------------- ### Connect to Redis Cluster with Config and Dotenvy Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Demonstrates setting up a connection pool for Redis Cluster using configuration loaded from environment variables via the `config` and `dotenvy` crates. Includes basic SET and GET operations. ```rust use deadpool_redis::redis::{cmd, FromRedisValue}; use deadpool_redis::cluster::{Runtime}; use dotenvy::dotenv; #[derive(Debug, serde::Deserialize)] struct Config { #[serde(default)] redis_cluster: deadpool_redis::cluster::Config } impl Config { pub fn from_env() -> Result { config::Config::builder() .add_source( config::Environment::default() .separator("__") .try_parsing(true) .list_separator(","), ) .build()? .try_deserialize() } } #[tokio::main] async fn main() { dotenv().ok(); let cfg = Config::from_env().unwrap(); let pool = cfg.redis_cluster.create_pool(Some(Runtime::Tokio1)).unwrap(); { let mut conn = pool.get().await.unwrap(); cmd("SET") .arg(&["deadpool/test_key", "42"]) .query_async::<()>(&mut conn) .await.unwrap(); } { let mut conn = pool.get().await.unwrap(); let value: String = cmd("GET") .arg(&["deadpool/test_key"]) .query_async(&mut conn) .await.unwrap(); assert_eq!(value, "42".to_string()); } } ``` -------------------------------- ### Loading Config from Environment Variables Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Config.html Demonstrates how to load the Config struct from environment variables using the `config` crate. This requires enabling the `serde` feature and setting environment variables with specific prefixes and separators. ```dotenv REDIS_SENTINEL__URLS=redis://127.0.0.1:26379,redis://127.0.0.1:26380 REDIS_SENTINEL__MASTER_NAME=mymaster REDIS_SENTINEL__SERVER_TYPE=master REDIS_SENTINEL__POOL__MAX_SIZE=16 REDIS_SENTINEL__POOL__TIMEOUTS__WAIT__SECS=2 REDIS_SENTINEL__POOL__TIMEOUTS__WAIT__NANOS=0 ``` ```rust #[derive(serde::Deserialize)] struct Config { redis_sentinel: deadpool_redis::sentinel::Config, } impl Config { pub fn from_env() -> Result { let mut cfg = config::Config::builder() .add_source( config::Environment::default() .separator("__") .try_parsing(true) .list_separator(","), ) .build()?; cfg.try_deserialize() } } ``` -------------------------------- ### GET Integer Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get a value from Redis and convert it to an `Option`. ```APIDOC ## GET Integer ### Description Get a value from Redis and convert it to an `Option`. ### Method `get_int` ### Parameters - `key`: The key of the value to retrieve. ### Return Value A future that resolves to an `Option` representing the integer value, or `None` if the key does not exist or the value is not an integer. ``` -------------------------------- ### from_urls Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/cluster/config.rs.html Creates a new `Config` instance initialized with a list of Redis URLs. ```APIDOC /// Creates a new [`Config`] from the given Redis URL (like /// `redis://127.0.0.1`). #[must_use] pub fn from_urls>>(urls: T) -> Config ``` -------------------------------- ### Hash Get Multiple Fields Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets multiple fields from a hash. ```APIDOC ## hmget ### Description Gets multiple fields from a hash. ### Method `hmget` ### Parameters - `key`: The key of the hash. - `fields`: The fields to retrieve from the hash. ``` -------------------------------- ### Connect to Redis Sentinel with Environment Variables Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Shows how to establish a connection pool for Redis Sentinel using URLs and master name from environment variables. It then performs a pipelined SET and GET operation. ```rust use std::env; use deadpool_redis::{redis::{cmd, FromRedisValue}, sentinel::SentinelServerType}; use deadpool_redis::sentinel::{Config, Runtime}; use dotenvy::dotenv; #[tokio::main] async fn main() { dotenv().ok(); use deadpool_redis::redis::pipe; let redis_urls = env::var("REDIS_SENTINEL__URLS") .unwrap() .split(',') .map(String::from) .collect::>(); let master_name = env::var("REDIS_SENTINEL__MASTER_NAME").unwrap(); let mut cfg = Config::from_urls(redis_urls, master_name, SentinelServerType::Master); let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap(); let mut conn = pool.get().await.unwrap(); let (value,): (String,) = pipe() .cmd("SET") .arg("deadpool/pipeline_test_key") .arg("42") .ignore() .cmd("GET") .arg("deadpool/pipeline_test_key") .query_async(&mut conn) .await .unwrap(); assert_eq!(value, "42".to_string()); } ``` -------------------------------- ### AsyncCommands - get Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Connection.html Get the value of a key. If key is a vec this becomes an `MGET` (if using `TypedCommands`, you should specifically use `mget` to get the correct return type. Redis Docs ```APIDOC ## fn get<'a, K, RV>( &'a mut self, key: K, ) -> Pin> + Send + 'a>> ### Description Get the value of a key. If key is a vec this becomes an `MGET` (if using `TypedCommands`, you should specifically use `mget` to get the correct return type. ### Parameters #### Path Parameters - **key** (K): The key to retrieve the value from. Must implement `ToSingleRedisArg`, `Send`, and `Sync`. ### Returns - `Pin> + Send + 'a>>`: A future that resolves to the value of the key, or a `RedisError`. ``` -------------------------------- ### Get Hash Field Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets a single field from a hash stored at a key. ```APIDOC ## hget ### Description Gets a single field from a hash. ### Method `hget` ### Parameters - `key`: The key of the hash. - `field`: The field to retrieve from the hash. ### Returns The value of the specified field. ``` -------------------------------- ### ClusterClientBuilder::new Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterClientBuilder.html Creates a new ClusterClientBuilder with the provided initial nodes. This is the entry point for building a ClusterClient. ```APIDOC ## ClusterClientBuilder::new ### Description Creates a new `ClusterClientBuilder` with the provided initial_nodes. This is the same as `ClusterClient::builder(initial_nodes)`. ### Signature ```rust pub fn new( initial_nodes: impl IntoIterator, ) -> ClusterClientBuilder where T: IntoConnectionInfo, ``` ``` -------------------------------- ### Create Config from URLs Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Config.html Factory method to create a new `Config` instance initialized with a list of Redis URLs. ```rust pub fn from_urls>>(urls: T) -> Config ``` -------------------------------- ### Get Multiple Hash Fields Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets multiple fields from a hash stored at a key. ```APIDOC ## hmget ### Description Gets multiple fields from a hash. ### Method `hmget` ### Parameters - `key`: The key of the hash. - `fields`: The fields to retrieve from the hash. ### Returns The values of the specified fields. ``` -------------------------------- ### Creating Config from URLs Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Config.html Provides a convenient way to create a `Config` object directly from a list of Redis URLs, a master name, and the server type. This is useful for simple configurations where environment variables are not used. ```rust pub fn from_urls>>( urls: T, master_name: String, server_type: SentinelServerType, ) -> Config ``` -------------------------------- ### Hash Get and Delete Field Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets and deletes the value of one or more fields of a given hash key. ```APIDOC ## hget_del ### Description Get and delete the value of one or more fields of a given hash key. ### Method `hget_del` ### Parameters - `key`: The key of the hash. - `fields`: The fields to get and delete from the hash. ``` -------------------------------- ### Create Config from ConnectionInfo Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Config.html Creates a new Config instance from a given Redis ConnectionInfo structure. ```rust pub fn from_connection_info>( connection_info: T, ) -> Config ``` -------------------------------- ### Get Hash Fields with Expiration Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Connection.html Gets the value of one or more fields of a given hash key and optionally sets their expiration. ```APIDOC ## hget_ex ### Description Get the value of one or more fields of a given hash key, and optionally set their expiration. ### Method `hget_ex` ### Parameters - `key`: The key of the hash. - `fields`: The fields to retrieve from the hash. - `expire_at`: The expiration time for the fields. ### Returns - `Result, RedisError>`: A vector of the values of the fields, or a RedisError. ``` -------------------------------- ### Connect to Redis Sentinel with Config and Dotenvy Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Illustrates creating a Redis Sentinel connection pool using a custom `Config` struct loaded from environment variables with `config` and `dotenvy`. It executes a pipelined SET and GET command. ```rust use serde::{Deserialize, Serialize}; use deadpool_redis::{redis, Runtime}; use dotenvy::dotenv; #[derive(Debug, Default, Deserialize, Serialize)] struct Config { #[serde(default)] redis_sentinel: deadpool_redis::sentinel::Config, } impl Config { pub fn from_env() -> Self { config::Config::builder() .add_source( config::Environment::default() .separator("__") .try_parsing(true) .list_separator(",") .with_list_parse_key("redis_sentinel.urls"), ) .build() .unwrap() .try_deserialize() .unwrap() } } fn create_pool() -> deadpool_redis::sentinel::Pool { let cfg = Config::from_env(); cfg.redis_sentinel .create_pool(Some(Runtime::Tokio1)) .unwrap() } #[tokio::main] async fn main() { dotenv().ok(); use deadpool_redis::redis::pipe; let pool = create_pool(); let mut conn = pool.get().await.unwrap(); let (value,): (String,) = pipe() .cmd("SET") .arg("deadpool/pipeline_test_key") .arg("42") .ignore() .cmd("GET") .arg("deadpool/pipeline_test_key") .query_async(&mut conn) .await .unwrap(); assert_eq!(value, "42".to_string()); } ``` -------------------------------- ### Hash Get Fields with Expiration Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets the value of one or more fields of a given hash key, and optionally sets their expiration. ```APIDOC ## hget_ex ### Description Get the value of one or more fields of a given hash key, and optionally set their expiration. ### Method `hget_ex` ### Parameters - `key`: The key of the hash. - `fields`: The fields to retrieve from the hash. - `expire_at`: The expiration time for the hash fields. ``` -------------------------------- ### Default ConnectionInfo Implementation Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.ConnectionInfo.html Provides a default value for `ConnectionInfo`. This is useful for creating a basic connection configuration when a specific one is not provided. ```rust impl Default for ConnectionInfo { fn default() -> ConnectionInfo { // ... implementation details ... } } ``` -------------------------------- ### from_urls Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/sentinel/config.rs.html Creates a new `Config` instance directly from a list of Redis URLs, master name, and server type. ```APIDOC ## from_urls ### Description Creates a new `Config` instance directly from a list of Redis URLs, master name, and server type. ### Method `#[must_use] pub fn from_urls>>( urls: T, master_name: String, server_type: SentinelServerType, ) -> Config` ### Parameters - **urls** (T: Into>) - A collection of Redis Sentinel URLs. - **master_name** (String) - The name of the master set in Sentinel. - **server_type** (SentinelServerType) - The type of Sentinel server. ### Returns - `Config` - A new configuration object. ``` -------------------------------- ### Get Hash Fields with Expiration Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets the value of one or more fields of a given hash key and optionally sets their expiration time. ```APIDOC ## hget_ex ### Description Get the value of one or more fields of a given hash key, and optionally set their expiration. ### Method `hget_ex` ### Parameters - `key`: The key of the hash. - `fields`: The fields to retrieve from the hash. - `expire_at`: The expiration time for the fields. ### Returns The values of the specified fields. ``` -------------------------------- ### Get PExpiration Time Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the absolute Unix expiration timestamp in milliseconds. Returns `ExistsButNotRelevant` if key exists but has no expiration time. ```APIDOC ## pexpire_time ### Description Get the absolute Unix expiration timestamp in milliseconds. Returns `ExistsButNotRelevant` if key exists but has no expiration time. ### Method `pexpire_time` ### Parameters - `key`: The key to get the expiration time for. ``` -------------------------------- ### PoolBuilder Configuration and Building Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/type.PoolBuilder.html Demonstrates how to configure and build a deadpool-redis Pool using the PoolBuilder. This includes setting pool size, timeouts, queue mode, and attaching hooks. ```APIDOC ## PoolBuilder Type alias for using `deadpool::managed::PoolBuilder` with `redis_sentinel`. ### Methods #### `fn config(self, value: PoolConfig) -> PoolBuilder` Sets a `PoolConfig` to build the `Pool` with. #### `fn max_size(self, value: usize) -> PoolBuilder` Sets the `PoolConfig::max_size`. #### `fn timeouts(self, value: Timeouts) -> PoolBuilder` Sets the `PoolConfig::timeouts`. #### `fn wait_timeout(self, value: Option) -> PoolBuilder` Sets the `Timeouts::wait` value of the `PoolConfig::timeouts`. #### `fn create_timeout(self, value: Option) -> PoolBuilder` Sets the `Timeouts::create` value of the `PoolConfig::timeouts`. #### `fn recycle_timeout(self, value: Option) -> PoolBuilder` Sets the `Timeouts::recycle` value of the `PoolConfig::timeouts`. #### `fn queue_mode(self, value: QueueMode) -> PoolBuilder` Sets the `PoolConfig::queue_mode`. #### `fn post_create(self, hook: impl Into>) -> PoolBuilder` Attaches a `post_create` hook. The given `hook` will be called each time right after a new `Object` has been created. #### `fn pre_recycle(self, hook: impl Into>) -> PoolBuilder` Attaches a `pre_recycle` hook. The given `hook` will be called each time right before an `Object` will be recycled. #### `fn post_recycle(self, hook: impl Into>) -> PoolBuilder` Attaches a `post_recycle` hook. The given `hook` will be called each time right after an `Object` has been recycled. #### `fn runtime(self, value: Runtime) -> PoolBuilder` Sets the `Runtime`. Important: The `Runtime` is optional. Most `Pool`s don’t need a `Runtime`. If you want to utilize timeouts, however, a `Runtime` must be specified as you will otherwise get a `PoolError::NoRuntimeSpecified` when trying to use `Pool::timeout_get()`. `PoolBuilder::build()` will fail with a `BuildError::NoRuntimeSpecified` if you try to build a `Pool` with timeouts and no `Runtime` specified. #### `fn build(self) -> Result, BuildError>` Builds the `Pool`. See `BuildError` for details on potential errors. ``` -------------------------------- ### create_pool Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/sentinel/config.rs.html Creates a new `Pool` using the provided `Config` and an optional `Runtime`. This is the primary method for initializing a connection pool. ```APIDOC ## create_pool ### Description Creates a new `Pool` using the provided `Config` and an optional `Runtime`. This is the primary method for initializing a connection pool. ### Method `pub fn create_pool(&self, runtime: Option) -> Result` ### Parameters - **runtime** (Option) - An optional runtime to use for the pool. ### Returns - `Result` - A `Pool` instance or a `CreatePoolError` if creation fails. ``` -------------------------------- ### Get Expiration Time Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the absolute Unix expiration timestamp in seconds. Returns `ExistsButNotRelevant` if key exists but has no expiration time. ```APIDOC ## expire_time ### Description Get the absolute Unix expiration timestamp in seconds. Returns `ExistsButNotRelevant` if key exists but has no expiration time. ### Method `expire_time` ### Parameters - `key`: The key to get the expiration time for. ``` -------------------------------- ### Implement From for SentinelNodeConnectionInfo (alternative) Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.SentinelNodeConnectionInfo.html Another implementation for converting SentinelNodeConnectionInfo to itself. ```rust fn from(_info: SentinelNodeConnectionInfo) -> Self ``` -------------------------------- ### JSON Array Index with Start and Stop Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Same as `json_arr_index` except takes a `start` and a `stop` value, setting these to `0` will mean they make no effect on the query. ```APIDOC ## JSON Array Index with Start and Stop ### Description Same as `json_arr_index` except takes a `start` and a `stop` value, setting these to `0` will mean they make no effect on the query. ### Method `json_arr_index_ss` ### Parameters - `key`: The key of the JSON document. - `path`: The JSON path to the array. - `value`: The JSON value to search for. - `start`: The starting index for the search. - `stop`: The stopping index for the search. ### Return Value A future that resolves to the result of the operation. ``` -------------------------------- ### from_url Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Config.html Creates a new `Config` from the given Redis URL. ```APIDOC #### pub fn from_url>(url: T) -> Config Creates a new `Config` from the given Redis URL (like `redis://127.0.0.1`). ``` -------------------------------- ### Default Config Implementation Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/config.rs.html Provides a default Config, using default ConnectionInfo. ```rust impl Default for Config { fn default() -> Self { Self { url: None, connection: Some(ConnectionInfo::default()), pool: None, } } } ``` -------------------------------- ### hlen Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets the length of a hash. ```APIDOC ## hlen ### Description Retrieves the number of fields stored within a hash. Returns 0 if the key does not exist. ### Method `hlen` ### Parameters - `key`: The key of the hash. ### Returns A future that resolves to the number of fields or a RedisError. ``` -------------------------------- ### Create a Pool Builder from Config Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/config.rs.html Constructs a PoolBuilder from the current Config, handling URL or ConnectionInfo and pool configuration. ```rust pub fn builder(&self) -> Result { let manager = match (&self.url, &self.connection) { (Some(url), None) => crate::Manager::new(url.as_str())?, (None, Some(connection)) => crate::Manager::new(connection.clone())?, (None, None) => crate::Manager::new(ConnectionInfo::default())?, (Some(_), Some(_)) => return Err(ConfigError::UrlAndConnectionSpecified), }; let pool_config = self.get_pool_config(); Ok(Pool::builder(manager).config(pool_config)) } ``` -------------------------------- ### Hvals Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets all the values in a hash. ```APIDOC ## hvals ### Description Gets all the values in a hash. ### Method `hvals` ### Parameters - `key`: The key of the hash. ### Returns A future that resolves to a list of all values in the hash. ``` -------------------------------- ### Create Config from URL Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Config.html Constructs a new Config instance directly from a Redis URL string. ```rust pub fn from_url>(url: T) -> Config ``` -------------------------------- ### mget Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get values of keys. ```APIDOC ## mget ### Description Get values of keys. ### Method `fn mget<'a, K, RV>(&'a mut self, key: K) -> Pin> + Send + 'a>>` ### Parameters #### Path Parameters - `key` (K: ToRedisArgs + Send + Sync + 'a) - Required - The keys to retrieve values from. ### Response #### Success Response (200) - `Pin> + Send + 'a>>` - A future that resolves to the values of the keys. ``` -------------------------------- ### From for ConnectionInfo Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.ConnectionInfo.html Provides an implementation for converting `ConnectionInfo` into itself. This is often a boilerplate implementation for trait consistency. ```rust impl From for ConnectionInfo { fn from(info: ConnectionInfo) -> Self { // ... implementation details ... } } ``` -------------------------------- ### Create a Pool from Config Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/cluster/config.rs.html Creates a new `Pool` instance using the current `Config` and an optional `Runtime`. Errors during configuration or building are mapped to `CreatePoolError`. ```rust pub fn create_pool(&self, runtime: Option) -> Result { let mut builder = self.builder().map_err(CreatePoolError::Config)?; if let Some(runtime) = runtime { builder = builder.runtime(runtime); } builder.build().map_err(CreatePoolError::Build) } ``` -------------------------------- ### Redis Connection Pool with Config and Dotenvy Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/index.html Shows how to configure the Redis pool using a custom struct, environment variables, and the dotenvy crate for loading .env files. Requires the 'config' and 'dotenvy' crates. ```rust use deadpool_redis::{redis::{cmd, FromRedisValue}, Runtime}; use dotenvy::dotenv; #[derive(Debug, serde::Deserialize)] struct Config { #[serde(default)] redis: deadpool_redis::Config } impl Config { pub fn from_env() -> Result { config::Config::builder() .add_source(config::Environment::default().separator("__")) .build()? .try_deserialize() } } #[tokio::main] async fn main() { dotenv().ok(); let cfg = Config::from_env().unwrap(); let pool = cfg.redis.create_pool(Some(Runtime::Tokio1)).unwrap(); { let mut conn = pool.get().await.unwrap(); cmd("SET") .arg(&["deadpool/test_key", "42"]) .query_async::<()>(&mut conn) .await.unwrap(); } { let mut conn = pool.get().await.unwrap(); let value: String = cmd("GET") .arg(&["deadpool/test_key"]) .query_async(&mut conn) .await.unwrap(); assert_eq!(value, "42".to_string()); } } ``` -------------------------------- ### SCAN OPTIONS Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Connection.html Incrementally iterates over the keyspace with specified options. ```APIDOC ## SCAN OPTIONS ### Description Incrementally iterates the keys space with options. ### Method `scan_options` ### Parameters - `opts`: `ScanOptions` for configuring the scan operation. ``` -------------------------------- ### get_del Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Get the value of a key and delete it. ```APIDOC ## get_del ### Description Get the value of a key and then delete the key from the store. ### Method `get_del` ### Parameters #### Path Parameters - **key** (K) - Required - The key whose value is to be retrieved and then deleted. ### Response #### Success Response (Result) - **RV** - The value of the key before deletion. #### Error Response (RedisError) - **RedisError** - An error that occurred during the operation. ``` -------------------------------- ### SCARD Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Get the number of members in a set. ```APIDOC ## SCARD ### Description Get the number of members in a set. ### Method `scard` ### Parameters - `key`: The key of the set. ### Returns A future that resolves to the number of members in the set. ``` -------------------------------- ### Create ClusterClientBuilder Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterClient.html Creates a `ClusterClientBuilder` with the provided initial nodes. The builder can then be used to configure and create the `ClusterClient`. ```rust pub fn builder( initial_nodes: impl IntoIterator, ) -> ClusterClientBuilder where T: IntoConnectionInfo, ``` -------------------------------- ### mset_ex Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterConnection.html Sets multiple keys with expiration and XX options. ```APIDOC ## mset_ex ### Description Sets the given keys to their respective values. This command is an extension of the MSETNX that adds expiration and XX options. ### Method `mset_ex` ### Parameters - `items`: A slice of key-value tuples to set. - `options`: The `MSetOptions` to apply. ### Returns A future that resolves to a Result containing a boolean indicating if the operation was successful, or a RedisError. ``` -------------------------------- ### keys Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.Connection.html Gets all keys matching pattern. ```APIDOC ## keys ### Description Gets all keys matching pattern. ### Method `fn keys<'a, K, RV>(&'a mut self, key: K) -> Pin> + Send + 'a>>` ### Parameters #### Path Parameters - `key` (K: ToSingleRedisArg + Send + Sync + 'a) - Required - The pattern to match keys against. ### Response #### Success Response (200) - `Pin> + Send + 'a>>` - A future that resolves to a list of keys matching the pattern. ``` -------------------------------- ### json_get Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Connection.html Gets a JSON value at the specified path. ```APIDOC ## fn json_get<'a, K, P, RV>( &'a mut self, key: K, path: P, ) -> Pin> + Send + 'a>> where K: ToSingleRedisArg + Send + Sync + 'a, P: ToRedisArgs + Send + Sync + 'a, RV: FromRedisValue, Gets JSON Value at `path`. Read more Source§ ``` -------------------------------- ### Create ClusterClient with default parameters Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/cluster/struct.ClusterClient.html Creates a `ClusterClient` with default parameters. This method only performs basic checks on the initial nodes' URLs and passwords/usernames; it does not establish connections to the Redis Cluster. ```rust pub fn new( initial_nodes: impl IntoIterator, ) -> Result where T: IntoConnectionInfo, ``` -------------------------------- ### from_connection_info Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Config.html Creates a new `Config` from the given Redis ConnectionInfo structure. ```APIDOC #### pub fn from_connection_info>( connection_info: T, ) -> Config Creates a new `Config` from the given Redis ConnectionInfo structure. ``` -------------------------------- ### pttl Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Connection.html Get the time to live for a key in milliseconds. ```APIDOC ## pttl ### Description Get the time to live for a key in milliseconds. Returns `ExistsButNotRelevant` if the key exists but has no expiration time. ### Method `pttl` ### Parameters - `key`: The key whose time to live is to be retrieved. ### Returns A future that resolves to an `IntegerReplyOrNoOp` indicating the time to live in milliseconds. ``` -------------------------------- ### srandmember Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/struct.Connection.html Get one random member from a set. ```APIDOC ## srandmember ### Description Get one random member from a set. ### Method `srandmember` ### Parameters - `key`: The key of the set. ### Response - Returns a random member from the set. ``` -------------------------------- ### Create Config from URLs Source: https://docs.rs/deadpool-redis/0.23.0/src/deadpool_redis/cluster/config.rs.html Constructs a `Config` object with a specified list of Redis URLs. Other configuration fields like `connections`, `pool`, and `read_from_replicas` are left at their default values. ```rust #[must_use] pub fn from_urls>>(urls: T) -> Config { Config { urls: Some(urls.into()), connections: None, pool: None, read_from_replicas: false, } } ``` -------------------------------- ### Manager::new Source: https://docs.rs/deadpool-redis/0.23.0/deadpool_redis/sentinel/struct.Manager.html Creates a new Manager instance for Sentinel connections. ```APIDOC ## Manager::new ### Description Creates a new `Manager` from the given `params`. ### Signature ```rust pub fn new( param: Vec, service_name: String, node_connection_info: Option, server_type: SentinelServerType, ) -> RedisResult ``` ### Parameters * `param`: A vector of connection info parameters. * `service_name`: The name of the Sentinel service. * `node_connection_info`: Optional information about the Sentinel node connection. * `server_type`: The type of Sentinel server. ### Returns A `RedisResult` containing the new `Manager` instance or an error if Sentinel client creation fails. ```