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
impl Client
Sourcepub async fn default() -> Result<Self>
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.
Sourcepub fn from_pool(pool: Pool) -> Self
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.
Sourcepub async fn from_url(url: &str) -> Result<Self>
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.
Sourcepub async fn connect(config: &Config) -> Result<Self>
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.
Sourcepub async fn connection(&self) -> Result<Connection>
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
impl Client
Sourcepub async fn get<V, K>(&self, key: K) -> Result<Option<V>>
pub async fn get<V, K>(&self, key: K) -> Result<Option<V>>
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(())
}Sourcepub 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,
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(())
}Sourcepub async fn get_ex<V, K>(&self, key: K, expire_at: Expiry) -> Result<Option<V>>
pub async fn get_ex<V, K>(&self, key: K, expire_at: Expiry) -> Result<Option<V>>
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- AnExpiryvalue 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(())
}Sourcepub async fn get_del<V, K>(&self, key: K) -> Result<Option<V>>
pub async fn get_del<V, K>(&self, key: K) -> Result<Option<V>>
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(())
}Sourcepub async fn getset<M, V>(&self, model: &M) -> Result<Option<V>>where
M: RedisModel,
V: RedisRead,
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
impl Client
Sourcepub async fn set<M>(&self, model: &M) -> Result<String>where
M: RedisModel,
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(())
}Sourcepub async fn mset<M, P>(&self, pairs: P) -> Result<String>
pub async fn mset<M, P>(&self, pairs: P) -> Result<String>
§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(())
}Sourcepub async fn mset_nx<M, P>(&self, pairs: P) -> Result<bool>
pub async fn mset_nx<M, P>(&self, pairs: P) -> Result<bool>
§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(())
}Sourcepub async fn set_nx<M>(&self, model: &M) -> Result<bool>where
M: RedisModel,
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(())
}Sourcepub async fn set_ex<M>(&self, model: &M, secs: u64) -> Result<String>where
M: RedisModel,
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
impl Client
Sourcepub async fn del<K>(&self, key: K) -> Result<bool>
pub async fn del<K>(&self, key: K) -> Result<bool>
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(())
}Sourcepub async fn mdel<K, T>(&self, keys: K) -> Result<usize>
pub async fn mdel<K, T>(&self, keys: K) -> Result<usize>
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
impl Client
Sourcepub async fn exists<K>(&self, key: K) -> Result<bool>
pub async fn exists<K>(&self, key: K) -> Result<bool>
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(())
}Sourcepub async fn ping(&self) -> Result<String>
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(())
}Sourcepub async fn rename<K1, K2>(&self, key: K1, new_key: K2) -> Result<String>
pub async fn rename<K1, K2>(&self, key: K1, new_key: K2) -> Result<String>
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(())
}Sourcepub async fn rename_nx<K1, K2>(&self, key: K1, new_key: K2) -> Result<bool>
pub async fn rename_nx<K1, K2>(&self, key: K1, new_key: K2) -> Result<bool>
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§
Auto Trait Implementations§
impl !RefUnwindSafe for Client
impl !UnwindSafe for Client
impl Freeze for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl UnsafeUnpin for Client
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
impl<T> ErasedDestructor for Twhere
T: 'static,
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>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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