#[allow(unused_imports)]
use redis::{
aio::MultiplexedConnection, AsyncCommands, Client, ConnectionAddr, ConnectionInfo,
RedisConnectionInfo,
};
use redlock::RedLock;
use std::{str::FromStr, sync::OnceLock};
use tracing::info;
#[derive(Clone)]
pub struct RedisPool {
pub client: Client,
pub connection: MultiplexedConnection,
pub redlock: RedLock,
}
static REDISPOOL: OnceLock<RedisPool> = OnceLock::<RedisPool>::new();
pub fn init_redis_pool(redis_url: String) -> &'static RedisPool {
REDISPOOL.get_or_init(|| {
let client_info = ConnectionInfo::from_str(&redis_url).unwrap();
let client = redis::Client::open(client_info).unwrap();
let connection = futures::executor::block_on(async {
client.get_multiplexed_async_connection().await.unwrap()
});
let redlock = redlock::RedLock::new(vec![redis_url]);
info!("connect to redis successfully");
RedisPool {
client: client,
connection: connection,
redlock: redlock,
}
})
}
pub fn get_redis_pool() -> &'static RedisPool {
REDISPOOL.get().unwrap()
}
pub async fn get_kv_cache(key: &String) -> anyhow::Result<String> {
let mut connection = get_redis_pool().connection.clone();
let res: String = connection.get(&key).await?;
Ok(res)
}
pub async fn set_kv_cache(key: &String, value: &String, ex: Option<u64>) -> anyhow::Result<()> {
let mut connection = get_redis_pool().connection.clone();
if ex.is_none() {
let _: () = connection.set(key, value).await?;
} else {
let _: () = connection.set_ex(key, value, ex.unwrap() as u64).await?;
}
Ok(())
}
pub async fn delete_kv_cache(key: &String) -> anyhow::Result<()> {
let mut connection = get_redis_pool().connection.clone();
let _: () = connection.del(key).await?;
Ok(())
}