1use super::Cache;
2pub use redis::{Commands, RedisError};
3
4#[derive(Clone)]
5pub struct RedisCache {
6 pub client: redis::Client,
7}
8
9impl Cache for RedisCache {
10 type Item = String;
11 type Client = redis::Connection;
12
13 async fn new() -> Self {
14 Self {
15 client: redis::Client::open("redis://127.0.0.1:6379").expect("ERROR_OISEAU_REDIS_CON"),
16 }
17 }
18
19 async fn get_con(&self) -> Self::Client {
20 self.client
21 .get_connection()
22 .expect("ERROR_OISEAU_PSQL_CON_ACQUIRE")
23 }
24
25 async fn get(&self, id: Self::Item) -> Option<String> {
26 self.get_con().await.get(id).ok()
27 }
28
29 async fn set(&self, id: Self::Item, content: Self::Item) -> bool {
30 let mut c = self.get_con().await;
31 let res: Result<String, RedisError> = c.set_ex(id, content, 604800);
32
33 res.is_ok()
34 }
35
36 async fn update(&self, id: Self::Item, content: Self::Item) -> bool {
37 self.set(id, content).await
38 }
39
40 async fn remove(&self, id: Self::Item) -> bool {
41 let mut c = self.get_con().await;
42 let res: Result<String, RedisError> = c.del(id);
43
44 res.is_ok()
45 }
46
47 async fn remove_starting_with(&self, id: Self::Item) -> bool {
48 let mut c = self.get_con().await;
49
50 let mut cmd = redis::cmd("DEL");
52 let keys: Result<Vec<String>, RedisError> = c.keys(id);
53
54 for key in keys.unwrap() {
55 cmd.arg(key);
56 }
57
58 let res: Result<String, RedisError> = cmd.query(&mut c);
60
61 res.is_ok()
62 }
63
64 async fn incr(&self, id: Self::Item) -> bool {
65 let mut c = self.get_con().await;
66 let res: Result<String, RedisError> = c.incr(id, 1);
67
68 res.is_ok()
69 }
70
71 async fn decr(&self, id: Self::Item) -> bool {
72 let mut c = self.get_con().await;
73 let res: Result<String, RedisError> = c.decr(id, 1);
74
75 res.is_ok()
76 }
77}