br_cache/
redis.rs

1use crate::CacheBase;
2use json::{array, object, JsonValue};
3use log::error;
4use redis::{Client, Commands, Connection, RedisResult};
5
6#[derive(Clone)]
7pub struct Redis {
8    client: Client,
9    db: i8,
10}
11
12impl Redis {
13    pub fn connect(dsn: String) -> Result<Self, String> {
14        // 读取配置
15        let client = Client::open(dsn);
16        match client {
17            Ok(client) => Ok(Self { client, db: 0 }),
18            Err(e) => Err(e.to_string()),
19        }
20    }
21    pub fn con(&mut self) -> Result<Connection, String> {
22        let conn = self.client.get_connection();
23        let mut conn = match conn {
24            Ok(e) => e,
25            Err(_) => return Err("Connection failed.".to_string()),
26        };
27        redis::pipe()
28            .cmd("SELECT")
29            .arg(self.db)
30            .exec(&mut conn)
31            .unwrap();
32        Ok(conn)
33    }
34}
35
36impl CacheBase for Redis {
37    /// 切换到指定的数据库
38    fn db(&mut self, db: i8) -> &mut Self {
39        self.db = db;
40        self
41    }
42
43    /// 设置
44    ///
45    /// * expiration_date 过期时间 s 秒
46    fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
47        let data: RedisResult<bool> = {
48            if expiration_date > 0 {
49                self.con()?.set_ex(key, value.to_string(), expiration_date)
50            } else {
51                self.con()?.set(key, value.to_string())
52            }
53        };
54        match data {
55            Ok(e) => Ok(e),
56            Err(e) => {
57                error!("{}", e);
58                Err(format!("设置缓存失败: {}", e))
59            }
60        }
61    }
62    /// 获取
63    fn get(&mut self, key: &str) -> Result<JsonValue, String> {
64        let data: RedisResult<String> = self.con()?.get(key);
65        match data {
66            Ok(e) => {
67                let res = match json::parse(&e) {
68                    Ok(json) => json,
69                    Err(_) => JsonValue::from(e),
70                };
71                Ok(res)
72            }
73            Err(e) => Err(format!("获取失败: {}", e)),
74        }
75    }
76    /// 删除
77    fn delete(&mut self, key: &str) -> Result<bool, String> {
78        let data: RedisResult<bool> = self.con()?.del(key);
79        match data {
80            Ok(e) => Ok(e),
81            Err(e) => Err(format!("delete error: {}", e)),
82        }
83    }
84    /// 判断KEY是否存在
85    fn exists(&mut self, key: &str) -> Result<bool, String> {
86        let data: RedisResult<bool> = self.con()?.exists(key);
87        match data {
88            Ok(data) => Ok(data),
89            Err(e) => Err(format!("判断是否存在失败: {}", e)),
90        }
91    }
92    /// 查询KEYS获取
93    fn keys(&mut self, key: &str) -> Result<JsonValue, String> {
94        let data: RedisResult<Vec<String>> = self.con()?.keys(key);
95        match data {
96            Ok(e) => Ok(JsonValue::from(e)),
97            Err(e) => Err(format!("查询KEYS失败: {}", e)),
98        }
99    }
100
101    /// 集合 添加
102    fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
103        let data: RedisResult<bool> = self.con()?.sadd(key, value.to_string());
104        match data {
105            Ok(e) => Ok(e),
106            Err(e) => Err(format!("集合添加: {}", e)),
107        }
108    }
109    /// 集合 获取
110    fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
111        let data: RedisResult<Vec<String>> = self.con()?.smembers(key);
112        match data {
113            Ok(e) => {
114                let mut list = array![];
115                for item in e.iter() {
116                    let data = JsonValue::from(item.clone());
117                    let json = json::parse(item).unwrap_or(data);
118                    let _ = list.push(json);
119                }
120                Ok(list)
121            }
122            Err(e) => Err(format!("集合查询: {}", e)),
123        }
124    }
125    /// 集合 删除
126    fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
127        let data: RedisResult<bool> = self.con()?.srem(key, value.to_string());
128        match data {
129            Ok(e) => Ok(e),
130            Err(e) => Err(format!("集合删除: {}", e)),
131        }
132    }
133
134    /// 设置消息队列
135    fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
136        let data: RedisResult<String> =
137            self.con()?
138                .xadd(key, "*", &[(value.to_string(), value.to_string())]);
139        let res = data.is_ok();
140        Ok(res)
141    }
142
143    /// 消息队列获取
144    fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String> {
145        let data: RedisResult<Vec<String>> = self.con()?.xread(&[key], &[0]);
146        match data {
147            Ok(e) => Ok(JsonValue::from(e)),
148            Err(e) => Err(format!("{}", e)),
149        }
150    }
151    // /// 订阅消息
152    // pub fn subscribe_s(&mut self, channel: &str, fun: fn(channel: &str, data: &str)) {
153    //     let mut pubsub = self.con.as_pubsub();
154    //     pubsub.subscribe(channel).unwrap();
155    //     loop {
156    //         let msg = pubsub.get_message().unwrap();
157    //         // 消息处理
158    //         let data: String = msg.get_payload().unwrap();
159    //         let channel = msg.get_channel_name();
160    //         fun(channel, data.as_str())
161    //     }
162    // }
163    // /// 发布消息
164    // pub fn publish(&mut self, key: &str, value: JsonValue) -> bool {
165    //     let data = self.con.publish(key, value.to_string());
166    //     return match data {
167    //         Ok(e) => {
168    //             e
169    //         }
170    //         Err(_e) => {
171    //             false
172    //         }
173    //     };
174    // }
175
176    /// 设置对象集合
177    fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
178        let data: RedisResult<bool> = self.con()?.hset(key, field, value.to_string());
179        match data {
180            Ok(e) => Ok(e),
181            Err(e) => Err(format!("{}", e)),
182        }
183    }
184    /// 获取对象集合
185    fn get_object(&mut self, key: &str) -> Result<JsonValue, String> {
186        let data: RedisResult<Vec<String>> = self.con()?.hgetall(key);
187        match data {
188            Ok(e) => {
189                let mut list = object! {};
190                let mut index = 0;
191                while index < e.len() {
192                    list[e[index].to_string()] = e[index + 1].clone().into();
193                    index += 2;
194                }
195                Ok(list)
196            }
197            Err(e) => Err(format!("{}", e)),
198        }
199    }
200
201    /// 哈希-添加
202    fn add_hash(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
203        let res: RedisResult<bool> = self.con()?.hexists(key, field);
204        let ists = res.unwrap_or(false);
205        if ists {
206            let res = self.delete_hash(key, field)?;
207            if res {
208                let data: RedisResult<bool> = self.con()?.hset(key, field, value.to_string());
209                match data {
210                    Ok(e) => Ok(e),
211                    Err(e) => {
212                        error!("{}", e);
213                        Err(format!("设置哈希类型缓存失败: {}", e))
214                    }
215                }
216            } else {
217                Ok(false)
218            }
219        } else {
220            let data: RedisResult<bool> = self.con()?.hset_nx(key, field, value.to_string());
221            match data {
222                Ok(e) => Ok(e),
223                Err(e) => {
224                    error!("{}", e);
225                    Err(format!("设置哈希类型缓存失败: {}", e))
226                }
227            }
228        }
229    }
230
231    fn get_hash_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
232        let data: RedisResult<String> = self.con()?.hget(key, field);
233        match data {
234            Ok(e) => Ok(json::parse(e.as_str()).unwrap_or(JsonValue::Null)),
235            Err(e) => {
236                error!("{}", e);
237                Err(format!("设置哈希类型缓存失败: {}", e))
238            }
239        }
240    }
241
242    fn get_hash_fields(&mut self, key: &str) -> Result<JsonValue, String> {
243        let data: RedisResult<Vec<String>> = self.con()?.hkeys(key);
244        match data {
245            Ok(e) => Ok(e.into()),
246            Err(e) => {
247                error!("{}", e);
248                Err(format!("获取哈希类型缓存失败: {}", e))
249            }
250        }
251    }
252
253    fn delete_hash(&mut self, key: &str, field: &str) -> Result<bool, String> {
254        let data: RedisResult<bool> = self.con()?.hdel(key, field);
255        match data {
256            Ok(e) => Ok(e),
257            Err(e) => {
258                error!("{}", e);
259                Err(format!("设置哈希类型缓存失败: {}", e))
260            }
261        }
262    }
263
264    fn get_hash_values(&mut self, key: &str) -> Result<JsonValue, String> {
265        let data: RedisResult<Vec<String>> = self.con()?.hvals(key);
266        match data {
267            Ok(e) => {
268                let mut list = array![];
269                for item in e.iter() {
270                    list.push(json::parse(item).unwrap_or(object! {}))
271                        .unwrap();
272                }
273                Ok(list)
274            }
275            Err(e) => {
276                error!("{}", e);
277                Err(format!("获取哈希类型缓存失败: {}", e))
278            }
279        }
280    }
281}