use std::sync::Arc;
use redis_tower_commands::Ping;
use redis_tower_core::{Command, ConnectionConfig, RedisConnection, RedisError};
use tokio::sync::Mutex;
#[derive(Clone)]
pub struct RedisClient {
pub(crate) inner: Arc<Mutex<RedisConnection>>,
}
impl RedisClient {
pub async fn connect(addr: &str) -> Result<Self, RedisError> {
let conn = RedisConnection::connect(addr).await?;
Ok(Self::from_connection(conn))
}
pub async fn connect_with_connection_config(
addr: &str,
config: &ConnectionConfig,
) -> Result<Self, RedisError> {
let conn = RedisConnection::connect_with_config(addr, config).await?;
Ok(Self::from_connection(conn))
}
pub async fn connect_url(url: &str) -> Result<Self, RedisError> {
let conn = RedisConnection::connect_url(url).await?;
Ok(Self::from_connection(conn))
}
pub async fn connect_url_with_connection_config(
url: &str,
config: &ConnectionConfig,
) -> Result<Self, RedisError> {
let conn = RedisConnection::connect_url_with_config(url, config).await?;
Ok(Self::from_connection(conn))
}
pub fn from_connection(conn: RedisConnection) -> Self {
Self {
inner: Arc::new(Mutex::new(conn)),
}
}
pub async fn execute<Cmd: Command>(&self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
let mut conn = self.inner.lock().await;
conn.execute(cmd).await
}
pub async fn health_check(&self) -> Result<(), RedisError> {
self.execute(Ping::new()).await?;
Ok(())
}
}