Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

A Redis client for managing connections to a Redis database.

The Client struct provides an interface for interacting with a Redis database using a connection pool. It allows for efficient management of multiple connections, enabling asynchronous operations without the overhead of creating new connections for each request.

§Fields

  • pool - A connection pool that manages the Redis connections. This pool allows for concurrent access to the Redis database, improving performance and resource utilization.

§Implementations

The Client struct includes methods for creating instances from default settings, specific URLs, or existing connection pools. It also provides methods for retrieving connections and performing various Redis operations.

§Example

use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new Redis client with default settings
    let client = Client::default().await?;

    // Use the client to perform Redis operations...

    Ok(())
}

Implementations§

Source§

impl Client

Source

pub async fn default() -> Result<Self>

Creates a new Client instance with default settings, connecting to Redis at the default address.

This asynchronous method initializes a Client by connecting to Redis at the specified default URL (redis://127.0.0.1:6379). It returns a Result containing the Client instance or an error if the connection fails.

§Returns

A Result<Self> where Self is the Client instance.

Source

pub fn from_pool(pool: Pool) -> Self

Creates a new Client instance from an existing connection pool.

This method initializes a Client using the provided Pool. It is a synchronous method and does not perform any network operations.

§Arguments
  • pool - The connection pool to use for Redis connections.
§Returns

A Client instance initialized with the provided pool.

Source

pub async fn from_url(url: &str) -> Result<Self>

Creates a new Client instance by connecting to Redis at the specified URL.

This asynchronous method initializes a Client by parsing the provided URL and creating a connection to Redis. It returns a Result containing the Client instance or an error if the connection fails.

§Arguments
  • url - The URL of the Redis server to connect to.
§Returns

A Result<Self> where Self is the Client instance.

Source

pub async fn connect(config: &Config) -> Result<Self>

Establishes a connection to Redis using the provided configuration.

This asynchronous method creates a connection pool based on the provided Config and returns a Client instance initialized with that pool. It returns a Result containing the Client instance or an error if the connection fails.

§Arguments
  • config - The configuration to use for connecting to Redis.
§Returns

A Result<Self> where Self is the Client instance.

Source

pub async fn connection(&self) -> Result<Connection>

Retrieves a connection from the connection pool.

This asynchronous method fetches a connection from the pool associated with the Client. It returns a Result containing the Connection or an error if the retrieval fails.

§Returns

A Result<Connection> where Connection is the retrieved connection from the pool.

Source§

impl Client

Source

pub async fn get<V, K>(&self, key: K) -> Result<Option<V>>
where V: RedisRead, K: for<'a> ToRedisArgs + Send + Sync,

Asynchronously retrieves a value from Redis using the provided key.

This method fetches the value associated with the specified key from Redis. If the key exists, it returns the value deserialized into the type V. The type V must implement the FromRedisValue trait.

§Arguments
  • key - A reference to a string slice that represents the key for which the value is to be retrieved.
§Returns

A Result containing an Option<V>, where Some(value) is the deserialized value if the key exists, or None if the key does not exist.

§Examples
use grapple_db::redis::Client;

// Assuming you have a type defined with trait `FromRedisValue` implemented

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let key = "some_key";
    let result: Option<MyValue> = client.get(key).await?;

    if let Some(value) = result {
        println!("Retrieved value: {:?}", value);
    } else {
        println!("No value found for key: {}", key);
    }

    Ok(())
}
Source

pub async fn mget<K, T, V>(&self, keys: K) -> Result<Vec<Option<V>>>
where V: RedisRead, K: IntoIterator<Item = T> + ToRedisArgs + Send + Sync, T: for<'a> ToRedisArgs + Send + Sync,

Asynchronously retrieves multiple values from Redis using the provided keys.

This method fetches the values associated with the specified keys from Redis. It returns a vector of Option<V>, where each Option contains the deserialized value if the corresponding key exists, or None if it does not. The type V must implement the FromRedisValue trait.

§Arguments
  • keys - An iterable collection of string slices representing the keys for which the values are to be retrieved.
§Returns

A Result containing a Vec<Option<V>>, where each element corresponds to a key in the input collection, with Some(value) for existing keys and None for non-existing keys.

§Examples
use grapple_db::redis::Client;

// Assuming you have a type defined with trait `FromRedisValue` implemented

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let keys = vec!["key1", "key2", "key3"];
    let results: Vec<Option<MyValue>> = client.mget(&keys).await?;

    for (key, value) in keys.iter().zip(results) {
        match value {
            Some(v) => println!("Retrieved value for {}: {:?}", key, v),
            None => println!("No value found for key: {}", key),
        }
    }

    Ok(())
}
Source

pub async fn get_ex<V, K>(&self, key: K, expire_at: Expiry) -> Result<Option<V>>
where V: RedisRead, K: for<'a> ToRedisArgs + Send + Sync,

Asynchronously retrieves a value from Redis using the provided key and sets an expiration time.

This method fetches the value associated with the specified key from Redis and sets an expiration time for that key. If the key exists, it returns the value deserialized into the type V. The type V must implement the FromRedisValue trait. The expire_at parameter specifies when the key should expire.

§Arguments
  • key - A reference to a string slice that represents the key for which the value is to be retrieved.
  • expire_at - An Expiry value indicating when the key should expire.
§Returns

A Result containing an Option<V>, where Some(value) is the deserialized value if the key exists, or None if the key does not exist.

§Examples
use grapple_db::redis::Client;

// Assuming you have a type defined with trait `FromRedisValue` implemented

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let key = "some_key";
    let expire_at = Expiry::EX(60); // Set expiration to 60 seconds
    let result: Option<MyValue> = client.get_ex(key, expire_at).await?;

    if let Some(value) = result {
        println!("Retrieved value: {:?}", value);
    } else {
        println!("No value found for key: {}", key);
    }

    Ok(())
}
Source

pub async fn get_del<V, K>(&self, key: K) -> Result<Option<V>>
where V: RedisRead, K: for<'a> ToRedisArgs + Send + Sync,

Asynchronously retrieves a value from Redis using the provided key and deletes the key.

This method fetches the value associated with the specified key from Redis and deletes the key in the process. If the key exists, it returns the value deserialized into the type V. The type V must implement the FromRedisValue trait.

§Arguments
  • key - A reference to a string slice that represents the key for which the value is to be retrieved and deleted.
§Returns

A Result containing an Option<V>, where Some(value) is the deserialized value if the key exists, or None if the key does not exist.

§Examples
use grapple_db::redis::Client;

// Assuming you have a type defined with trait `FromRedisValue` implemented

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let key = "some_key";
    let result: Option<MyValue> = client.get_del(key).await?;

    if let Some(value) = result {
        println!("Retrieved and deleted value: {:?}", value);
    } else {
        println!("No value found for key: {}", key);
    }

    Ok(())
}
Source

pub async fn getset<M, V>(&self, model: &M) -> Result<Option<V>>
where M: RedisModel, V: RedisRead,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model = MyModel { a: 42 };
    let old_value: Option<MyModel> = client.getset(&model).await?;
    Ok(())
}
Source§

impl Client

Source

pub async fn set<M>(&self, model: &M) -> Result<String>
where M: RedisModel,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model = MyModel { a: 42 };
    let result: String = client.set(&model).await?;
    Ok(())
}
Source

pub async fn mset<M, P>(&self, pairs: P) -> Result<String>
where M: RedisModel, P: AsRedisPairs<M> + Send + Sync,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model1 = MyModel { a: 1 };
    let model2 = MyModel { a: 2 };

    // Используем кортежи для mset
    let tuple1 = (model1.key().unwrap(), serde_json::to_string(&model1).unwrap());
    let tuple2 = (model2.key().unwrap(), serde_json::to_string(&model2).unwrap());
    let result: String = client.mset([&tuple1, &tuple2]).await?;
    Ok(())
}
Source

pub async fn mset_nx<M, P>(&self, pairs: P) -> Result<bool>
where M: RedisModel, P: AsRedisPairs<M> + Send + Sync,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model1 = MyModel { a: 1 };
    let model2 = MyModel { a: 2 };

    // Используем кортежи для mset_nx
    let tuple1 = (model1.key().unwrap(), serde_json::to_string(&model1).unwrap());
    let tuple2 = (model2.key().unwrap(), serde_json::to_string(&model2).unwrap());
    let result: bool = client.mset_nx([&tuple1, &tuple2]).await?;
    Ok(())
}
Source

pub async fn set_nx<M>(&self, model: &M) -> Result<bool>
where M: RedisModel,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model = MyModel { a: 42 };
    let result: bool = client.set_nx(&model).await?;
    Ok(())
}
Source

pub async fn set_ex<M>(&self, model: &M, secs: u64) -> Result<String>
where M: RedisModel,

§Examples
use grapple_db::redis;
use grapple_db::redis::Client;
use grapple_db::redis::RedisModel;
use grapple_db::redis::macros::FromRedisValue;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, FromRedisValue)]
struct MyModel {
    a: u64,
}

impl RedisModel for MyModel {
    type Key = String;
    type Value = String;

    fn key(&self) -> grapple_db::redis::Result<Self::Key> {
        Ok(self.a.to_string())
    }

    fn key_ref(&self) -> &Self::Key {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }

    fn value(&self) -> grapple_db::redis::Result<impl deadpool_redis::redis::ToRedisArgs + Send + Sync> {
        Ok(serde_json::to_string(&self)?)
    }

    fn value_ref(&self) -> &Self::Value {
        static PLACEHOLDER: String = String::new();
        &PLACEHOLDER
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;
    let model = MyModel { a: 42 };
    let result: String = client.set_ex(&model, 60).await?;
    Ok(())
}
Source§

impl Client

Source

pub async fn del<K>(&self, key: K) -> Result<bool>
where K: for<'a> ToRedisArgs + Send + Sync,

Asynchronously deletes a key from Redis.

This method removes the specified key from Redis. If the key exists and is successfully deleted, it returns the true, if the key does not exist, it returns false.

§Arguments
  • key - The key to be deleted from Redis.
§Returns

A Result containing a bool, which indicates if the entity was removed. This will be true if the key was successfully deleted, or false if the key did not exist.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let result: bool = client.del("my_key").await?;

    Ok(())
}
Source

pub async fn mdel<K, T>(&self, keys: K) -> Result<usize>
where K: IntoIterator<Item = T>, T: for<'a> ToRedisArgs + Send + Sync,

Asynchronously deletes multiple keys from Redis.

This method removes the specified keys from Redis. It takes an iterable collection of keys and attempts to delete each one. The method returns the total number of keys that were successfully removed. If a key does not exist, it is simply ignored in the count.

§Arguments
  • keys - An iterable collection of keys to be deleted from Redis.
§Returns

A Result containing a usize, which indicates the number of keys that were successfully removed. This count reflects only the keys that existed and were deleted.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let deleted_count: usize = client.mdel(vec!["key1", "key2", "key3"]).await?;

    Ok(())
}
Source§

impl Client

Source

pub async fn exists<K>(&self, key: K) -> Result<bool>
where K: for<'a> ToRedisArgs + Send + Sync,

Asynchronously checks if a key exists in Redis.

This method checks whether the specified key is present in Redis. If the key exists, it returns true; otherwise, it returns false.

§Arguments
  • key - The key to check for existence in Redis.
§Returns

A Result containing a bool, where true indicates that the key exists, and false indicates that it does not.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let exists: bool = client.exists("my_key").await?;

    Ok(())
}
Source

pub async fn ping(&self) -> Result<String>

Asynchronously sends a ping command to Redis to check the connection.

This method sends a ping command to the Redis server. If the server is reachable and responsive, it returns a confirmation message (usually “PONG”). If there is an issue with the connection, an error will be returned.

§Returns

A Result containing a String, which is the response from the Redis server, typically “PONG”.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let response: String = client.ping().await?;

    Ok(())
}
Source

pub async fn rename<K1, K2>(&self, key: K1, new_key: K2) -> Result<String>
where K1: for<'a> ToRedisArgs + Send + Sync, K2: for<'a> ToRedisArgs + Send + Sync,

Asynchronously renames a key in Redis.

This method renames the specified key to a new key. If the operation is successful, it returns a confirmation message. If the new key already exists, it will be overwritten.

§Arguments
  • key - The current key to be renamed.
  • new_key - The new key name to assign.
§Returns

A Result containing a String confirmation message indicating the success of the operation.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let response: String = client.rename("old_key", "new_key").await?;

    Ok(())
}
Source

pub async fn rename_nx<K1, K2>(&self, key: K1, new_key: K2) -> Result<bool>
where K1: for<'a> ToRedisArgs + Send + Sync, K2: for<'a> ToRedisArgs + Send + Sync,

Asynchronously renames a key in Redis only if the new key does not already exist.

This method attempts to rename the specified key to a new key name, but only if the new key does not already exist in Redis. If the operation is successful and the new key was created, it returns true. If the new key already exists, it does not perform the rename and returns false.

§Arguments
  • key - The current key to be renamed.
  • new_key - The new key name to assign.
§Returns

A Result containing a bool, where true indicates that the rename was successful, and false indicates that the new key already existed.

§Examples
use grapple_db::redis::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::default().await?;

    let success: bool = client.rename_nx("old_key", "new_key").await?;

    Ok(())
}

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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