use super::Cache;
pub use redis::{Commands, RedisError};
#[derive(Clone)]
pub struct RedisCache {
pub client: redis::Client,
}
impl Cache for RedisCache {
type Item = String;
type Client = redis::Connection;
async fn new() -> Self {
Self {
client: redis::Client::open("redis://127.0.0.1:6379").expect("ERROR_OISEAU_REDIS_CON"),
}
}
async fn get_con(&self) -> Self::Client {
self.client
.get_connection()
.expect("ERROR_OISEAU_REDIS_CON_ACQUIRE")
}
async fn get(&self, id: Self::Item) -> Option<String> {
self.get_con().await.get(id).ok()
}
async fn set(&self, id: Self::Item, content: Self::Item) -> bool {
let mut c = self.get_con().await;
let res: Result<String, RedisError> = c.set_ex(id, content, 604800);
res.is_ok()
}
async fn update(&self, id: Self::Item, content: Self::Item) -> bool {
self.set(id, content).await
}
async fn remove(&self, id: Self::Item) -> bool {
let mut c = self.get_con().await;
let res: Result<String, RedisError> = c.del(id);
res.is_ok()
}
async fn remove_starting_with(&self, id: Self::Item) -> bool {
let mut c = self.get_con().await;
let mut cmd = redis::cmd("DEL");
let keys: Result<Vec<String>, RedisError> = c.keys(id);
for key in keys.unwrap() {
cmd.arg(key);
}
let res: Result<String, RedisError> = cmd.query(&mut c);
res.is_ok()
}
async fn incr(&self, id: Self::Item) -> bool {
let mut c = self.get_con().await;
let res: Result<String, RedisError> = c.incr(id, 1);
res.is_ok()
}
async fn decr(&self, id: Self::Item) -> bool {
let mut c = self.get_con().await;
let res: Result<String, RedisError> = c.decr(id, 1);
res.is_ok()
}
}