br_cache/
lib.rs

1use crate::redis::Redis;
2use json::{JsonValue};
3use std::sync::RwLock;
4use once_cell::sync::Lazy;
5pub use crate::config::{CacheMode, Config, Connection};
6
7pub mod config;
8mod redis;
9
10static GLOBAL_CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| {
11    RwLock::new(Config::default())
12});
13
14#[derive(Clone)]
15pub enum Cache {
16    Redis(Redis),
17    None,
18}
19
20impl Cache {
21    /// 配置文件模式
22    pub fn new(config: Config) -> Self {
23        {
24            let mut data = GLOBAL_CONFIG.write().unwrap();
25            data.clone_from(&config);
26        }
27        let config = GLOBAL_CONFIG.read().unwrap();
28        let connection = config.connections.get(config.default.as_str()).unwrap().clone();
29        match connection.mode {
30            CacheMode::Redis => {
31                match Redis::connect(connection) {
32                    Ok(e) => Cache::Redis(e),
33                    Err(_) => Cache::None
34                }
35            }
36            CacheMode::None => Cache::None
37        }
38    }
39
40    /// 非配置文件模式
41    pub fn create(name: &str, connection: Connection) -> Self {
42        {
43            let mut data = GLOBAL_CONFIG.write().unwrap();
44            if !data.connections.contains_key(name) {
45                data.connections.insert(name.to_string(), connection);
46            }
47            data.default = name.to_string();
48        }
49        let config = GLOBAL_CONFIG.read().unwrap();
50        let connection = config.connections.get(config.default.as_str()).unwrap().clone();
51        match connection.mode {
52            CacheMode::Redis => {
53                match Redis::connect(connection) {
54                    Ok(e) => Cache::Redis(e),
55                    Err(_) => Cache::None
56                }
57            }
58            CacheMode::None => Cache::None
59        }
60    }
61    /// 获取通道列表
62    pub fn connections(&mut self) -> JsonValue {
63        let mut connections = vec![];
64        let data = GLOBAL_CONFIG.read().unwrap();
65        for (item, mut value) in data.connections.clone() {
66            if value.mode.str().is_empty() {
67                continue;
68            }
69            let mut t = value.json();
70            t["name"] = item.into();
71            connections.push(t);
72        }
73        connections.into()
74    }
75    /// 切换通道
76    pub fn connection(&mut self, name: &str) -> Self {
77        let mut data = GLOBAL_CONFIG.write().unwrap();
78        if data.connections.contains_key(name) {
79            if name == data.default {
80                return self.clone();
81            }
82            data.default = name.to_string();
83            let connection = data.connections.get(data.default.as_str()).unwrap().clone();
84            match connection.mode {
85                CacheMode::Redis => {
86                    match Redis::connect(connection) {
87                        Ok(e) => Cache::Redis(e),
88                        Err(_) => Cache::None
89                    }
90                }
91                CacheMode::None => Cache::None
92            }
93        } else {
94            Cache::None
95        }
96    }
97}
98
99
100pub trait CacheBase {
101    /// 选择数据库
102    fn db(&mut self, db: i8) -> &mut Self;
103
104    /// 键 判断是否存在
105    fn key_exists(&mut self, key: &str) -> Result<bool, String>;
106    /// 键 删除
107    fn key_del(&mut self, key: &str) -> Result<bool, String>;
108    /// 键 以秒为单位返回 key 的剩余过期时间。
109    fn key_ttl(&mut self, key: &str) -> Result<i64, String>;
110
111    /// 键 设置到期时间
112    /// * key 键
113    /// * timestamp 到期时间戳 10位
114    fn key_set_expireat(&mut self, key: &str, timestamp: i64) -> Result<bool, String>;
115    /// 键 设置到期时间
116    /// * s 过期秒
117    fn key_set_seconds(&mut self, key: &str, s: i64) -> Result<bool, String>;
118    /// 键 删除到期时间
119    fn key_del_expire(&mut self, key: &str) -> Result<bool, String>;
120    /// 查询 KEY
121    /// * key 键 格式 * 或 *#### 模糊查询
122    fn key_query(&mut self, key: &str) -> Result<JsonValue, String>;
123
124    /// 设置缓存
125    ///
126    /// * expiration_date 过期时间 s 秒
127    fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String>;
128    /// 获取缓存
129    fn get(&mut self, key: &str) -> Result<JsonValue, String>;
130
131    /// 集合 添加
132    fn set_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
133    /// 集合 获取成员数量
134    fn set_count(&mut self, key: &str) -> Result<usize, String>;
135    /// 集合 获取
136    fn set_get(&mut self, key: &str) -> Result<JsonValue, String>;
137    /// 集合 删除
138    fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
139    /// 集合 获取交集
140    fn set_get_sinter(&mut self, keys: Vec<&str>) -> Result<JsonValue, String>;
141    /// 集合 获取并集
142    fn set_get_sunion(&mut self, keys: Vec<&str>) -> Result<JsonValue, String>;
143
144    /// 列表 添加
145    fn list_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
146    /// 列表 删除元素
147    fn list_del(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
148    /// 从列表左侧添加元素
149    fn list_lpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
150    /// 从列表右侧添加元素
151    fn list_rpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
152    /// 从列表左侧弹出元素
153    /// count: 0 = 弹出1个(兼容旧版),>0 = 弹出指定数量
154    fn list_lpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String>;
155    /// 从列表右侧弹出元素
156    fn list_rpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String>;
157    /// 获取列表长度
158    fn list_len(&mut self, key: &str) -> Result<usize, String>;
159    /// 获取列表指定范围的元素
160    fn list_range(&mut self, key: &str, start: isize, stop: isize) -> Result<Vec<JsonValue>, String>;
161    /// 获取列表所有元素
162    fn list_all(&mut self, key: &str) -> Result<Vec<JsonValue>, String>;
163    /// 根据索引获取列表元素
164    fn list_get(&mut self, key: &str, index: isize) -> Result<JsonValue, String>;
165    /// 修剪列表,只保留指定范围内的元素
166    fn list_trim(&mut self, key: &str, start: isize, stop: isize) -> Result<bool, String>;
167    /// 设置指定索引位置的元素值
168    fn list_set(&mut self, key: &str, index: isize, value: JsonValue) -> Result<bool, String>;
169    /// 删除列表中指定值的元素(count=0表示删除所有匹配项)
170    fn list_remove(&mut self, key: &str, value: JsonValue, count: isize) -> Result<isize, String>;
171    /// 获取哈希值
172    fn hash_get(&mut self, key: &str) -> Result<JsonValue, String>;
173    /// 添加哈希
174    fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
175    /// 获取哈希指定key的字段值
176    fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String>;
177    /// 获取key下所有的field
178    fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String>;
179    /// 删除哈希指定key的字段
180    fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String>;
181    /// 获取key下所有的value
182    fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String>;
183    /// 地理 添加地理位置
184    fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String>;
185    /// 地理 获取地理位置
186    fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String>;
187    /// 地理 获取两地之间的距离地理位置
188    fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String>;
189    /// 地理 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素
190    fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String>;
191
192    /// 设置消息队列
193    fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String>;
194    /// 获取消息长度
195    fn stream_count(&mut self, key: &str) -> Result<usize, String>;
196    /// 获取 过滤已删除的消息队列
197    fn stream_get(&mut self, key: &str) -> Result<JsonValue, String>;
198    /// 删除消息
199    fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String>;
200
201    /// 创建消费者组
202    fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String>;
203    fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
204    fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
205    /// 删除 消费者
206    fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String>;
207    /// 删除 消费者
208    fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String>;
209    /// 获取组存在不
210    fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String>;
211
212    fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String>;
213}
214
215impl Cache {
216    pub fn db(&mut self, db: i8) -> &mut Self {
217        match self {
218            Cache::Redis(e) => {
219                e.db(db);
220            }
221            Cache::None => {}
222        }
223        self
224    }
225
226    pub fn key_exists(&mut self, key: &str) -> Result<bool, String> {
227        Ok(match self {
228            Cache::Redis(e) => e.key_exists(key)?,
229            Cache::None => return Err("error".to_string()),
230        })
231    }
232
233    pub fn key_del(&mut self, key: &str) -> Result<bool, String> {
234        Ok(match self {
235            Cache::Redis(e) => e.key_del(key)?,
236            Cache::None => return Err("error".to_string()),
237        })
238    }
239
240    pub fn key_ttl(&mut self, key: &str) -> Result<i64, String> {
241        Ok(match self {
242            Cache::Redis(e) => e.key_ttl(key)?,
243            Cache::None => return Err("error".to_string()),
244        })
245    }
246
247
248    pub fn key_set_expireat(&mut self, key: &str, timestamp: i64) -> Result<bool, String> {
249        Ok(match self {
250            Cache::Redis(e) => e.key_set_expireat(key, timestamp)?,
251            Cache::None => return Err("error".to_string()),
252        })
253    }
254
255    pub fn key_set_seconds(&mut self, key: &str, s: i64) -> Result<bool, String> {
256        Ok(match self {
257            Cache::Redis(e) => e.key_set_seconds(key, s)?,
258            Cache::None => return Err("error".to_string()),
259        })
260    }
261
262    pub fn key_del_expire(&mut self, key: &str) -> Result<bool, String> {
263        Ok(match self {
264            Cache::Redis(e) => e.key_del_expire(key)?,
265            Cache::None => return Err("error".to_string()),
266        })
267    }
268
269    pub fn key_query(&mut self, key: &str) -> Result<JsonValue, String> {
270        let res = match self {
271            Cache::Redis(e) => e.key_query(key)?,
272            Cache::None => return Err("error".to_string()),
273        };
274        Ok(res)
275    }
276    pub fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
277        Ok(match self {
278            Cache::Redis(e) => e.add(key, value, expiration_date)?,
279            Cache::None => return Err("error".to_string()),
280        })
281    }
282    pub fn get(&mut self, key: &str) -> Result<JsonValue, String> {
283        let res = match self {
284            Cache::Redis(e) => e.get(key)?,
285            Cache::None => return Err("error".to_string()),
286        };
287        Ok(res)
288    }
289
290
291    pub fn set_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
292        let res = match self {
293            Cache::Redis(e) => e.set_add(key, value, expiry_s)?,
294            Cache::None => return Err("error".to_string()),
295        };
296        Ok(res)
297    }
298    pub fn set_count(&mut self, key: &str) -> Result<usize, String> {
299        let res = match self {
300            Cache::Redis(e) => e.set_count(key)?,
301            Cache::None => return Err("error".to_string()),
302        };
303        Ok(res)
304    }
305    pub fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
306        let res = match self {
307            Cache::Redis(e) => e.set_get(key)?,
308            Cache::None => return Err("error".to_string()),
309        };
310        Ok(res)
311    }
312
313    pub fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
314        Ok(match self {
315            Cache::Redis(e) => e.set_delete(key, value)?,
316            Cache::None => return Err("error".to_string()),
317        })
318    }
319
320    pub fn set_get_sinter(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
321        Ok(match self {
322            Cache::Redis(e) => e.set_get_sinter(keys)?,
323            Cache::None => return Err("error".to_string()),
324        })
325    }
326
327    pub fn set_get_sunion(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
328        Ok(match self {
329            Cache::Redis(e) => e.set_get_sunion(keys)?,
330            Cache::None => return Err("error".to_string()),
331        })
332    }
333
334    pub fn list_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
335        Ok(match self {
336            Cache::Redis(e) => e.list_add(key, value, expiry_s)?,
337            Cache::None => return Err("error".to_string()),
338        })
339    }
340
341    pub fn list_del(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
342        Ok(match self {
343            Cache::Redis(e) => e.list_del(key, value)?,
344            Cache::None => return Err("error".to_string()),
345        })
346    }
347
348    /// 从列表左侧添加元素
349    pub fn list_lpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
350        Ok(match self {
351            Cache::Redis(e) => e.list_lpush(key, value, expiry_s)?,
352            Cache::None => return Err("Redis连接未初始化".to_string()),
353        })
354    }
355
356    /// 从列表右侧添加元素
357    pub fn list_rpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
358        Ok(match self {
359            Cache::Redis(e) => e.list_rpush(key, value, expiry_s)?,
360            Cache::None => return Err("Redis连接未初始化".to_string()),
361        })
362    }
363
364    /// 从列表左侧弹出多个元素
365    pub fn list_lpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String> {
366        Ok(match self {
367            Cache::Redis(e) => e.list_lpop(key, count)?,
368            Cache::None => return Err("Redis连接未初始化".to_string()),
369        })
370    }
371    
372    /// 从列表右侧弹出多个元素
373    pub fn list_rpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String> {
374        Ok(match self {
375            Cache::Redis(e) => e.list_rpop(key, count)?,
376            Cache::None => return Err("Redis连接未初始化".to_string()),
377        })
378    }
379
380    /// 获取列表长度
381    pub fn list_len(&mut self, key: &str) -> Result<usize, String> {
382        Ok(match self {
383            Cache::Redis(e) => e.list_len(key)?,
384            Cache::None => return Err("Redis连接未初始化".to_string()),
385        })
386    }
387
388    /// 获取列表指定范围的元素
389    pub fn list_range(&mut self, key: &str, start: isize, stop: isize) -> Result<Vec<JsonValue>, String> {
390        Ok(match self {
391            Cache::Redis(e) => e.list_range(key, start, stop)?,
392            Cache::None => return Err("Redis连接未初始化".to_string()),
393        })
394    }
395
396    /// 获取列表所有元素
397    pub fn list_all(&mut self, key: &str) -> Result<Vec<JsonValue>, String> {
398        Ok(match self {
399            Cache::Redis(e) => e.list_all(key)?,
400            Cache::None => return Err("Redis连接未初始化".to_string()),
401        })
402    }
403
404    /// 根据索引获取列表元素(返回JsonValue)
405    pub fn list_get(&mut self, key: &str, index: isize) -> Result<JsonValue, String> {
406        Ok(match self {
407            Cache::Redis(e) => e.list_get(key, index)?,
408            Cache::None => return Err("Redis连接未初始化".to_string()),
409        })
410    }
411
412    /// 修剪列表,只保留指定范围内的元素
413    pub fn list_trim(&mut self, key: &str, start: isize, stop: isize) -> Result<bool, String> {
414        Ok(match self {
415            Cache::Redis(e) => e.list_trim(key, start, stop)?,
416            Cache::None => return Err("Redis连接未初始化".to_string()),
417        })
418    }
419
420    /// 设置指定索引位置的元素值
421    pub fn list_set(&mut self, key: &str, index: isize, value: JsonValue) -> Result<bool, String> {
422        Ok(match self {
423            Cache::Redis(e) => e.list_set(key, index, value)?,
424            Cache::None => return Err("Redis连接未初始化".to_string()),
425        })
426    }
427
428    /// 删除列表中指定值的元素
429    pub fn list_remove(&mut self, key: &str, value: JsonValue, count: isize) -> Result<isize, String> {
430        Ok(match self {
431            Cache::Redis(e) => e.list_remove(key, value, count)?,
432            Cache::None => return Err("Redis连接未初始化".to_string()),
433        })
434    }
435    
436
437    /// 哈希 获取
438    pub fn hash_get(&mut self, key: &str) -> Result<JsonValue, String> {
439        let res = match self {
440            Cache::Redis(e) => e.hash_get(key)?,
441            Cache::None => return Err("error".to_string()),
442        };
443        Ok(res)
444    }
445    /// 哈希 添加
446    pub fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
447        Ok(match self {
448            Cache::Redis(e) => e.hash_add(key, field, value)?,
449            Cache::None => return Err("error".to_string()),
450        })
451    }
452    /// 哈希-获取指定字段的值
453    pub fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
454        let res = match self {
455            Cache::Redis(e) => e.hash_get_field_value(key, field)?,
456            Cache::None => return Err("error".to_string()),
457        };
458        Ok(res)
459    }
460    /// 哈希-获取所有字段
461    pub fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String> {
462        Ok(match self {
463            Cache::Redis(e) => e.hash_get_fields(key)?,
464            Cache::None => return Err("error".to_string()),
465        })
466    }
467    pub fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String> {
468        Ok(match self {
469            Cache::Redis(e) => e.hash_delete(key, field)?,
470            Cache::None => return Err("error".to_string()),
471        })
472    }
473    /// 哈希-获取所有值
474    pub fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String> {
475        Ok(match self {
476            Cache::Redis(e) => e.hash_get_values(key)?,
477            Cache::None => return Err("error".to_string()),
478        })
479    }
480
481    pub fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String> {
482        Ok(match self {
483            Cache::Redis(e) => e.geo_add(key, longitude, latitude, value)?,
484            Cache::None => return Err("error".to_string()),
485        })
486    }
487
488
489    pub fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String> {
490        Ok(match self {
491            Cache::Redis(e) => e.geo_get(key, value)?,
492            Cache::None => return Err("error".to_string()),
493        })
494    }
495
496    pub fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String> {
497        Ok(match self {
498            Cache::Redis(e) => e.geo_dist(key, value1, value2)?,
499            Cache::None => return Err("error".to_string()),
500        })
501    }
502
503    pub fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String> {
504        Ok(match self {
505            Cache::Redis(e) => e.geo_radius(key, value, radius)?,
506            Cache::None => return Err("error".to_string()),
507        })
508    }
509    pub fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String> {
510        match self {
511            Cache::Redis(e) => e.stream_add(key, msg_id, field, value),
512            Cache::None => Err("error".to_string()),
513        }
514    }
515    pub fn stream_count(&mut self, key: &str) -> Result<usize, String> {
516        Ok(match self {
517            Cache::Redis(e) => e.stream_count(key)?,
518            Cache::None => return Err("error".to_string()),
519        })
520    }
521
522    pub fn stream_get(&mut self, key: &str) -> Result<JsonValue, String> {
523        Ok(match self {
524            Cache::Redis(e) => e.stream_get(key)?,
525            Cache::None => return Err("error".to_string()),
526        })
527    }
528
529
530    pub fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String> {
531        Ok(match self {
532            Cache::Redis(e) => e.stream_del(key, id)?,
533            Cache::None => return Err("error".to_string()),
534        })
535    }
536
537    pub fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String> {
538        Ok(match self {
539            Cache::Redis(e) => e.stream_group_create(key, group)?,
540            Cache::None => return Err("error".to_string()),
541        })
542    }
543
544    pub fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
545        Ok(match self {
546            Cache::Redis(e) => e.stream_group_add_user(key, group, user)?,
547            Cache::None => return Err("error".to_string()),
548        })
549    }
550
551    pub fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
552        Ok(match self {
553            Cache::Redis(e) => e.stream_group_del_user(key, group, user)?,
554            Cache::None => return Err("error".to_string()),
555        })
556    }
557
558    pub fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String> {
559        Ok(match self {
560            Cache::Redis(e) => e.stream_group_del(key, group)?,
561            Cache::None => return Err("error".to_string()),
562        })
563    }
564
565    pub fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String> {
566        Ok(match self {
567            Cache::Redis(e) => e.stream_group_msg(key, group, user)?,
568            Cache::None => return Err("error".to_string()),
569        })
570    }
571
572    pub fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String> {
573        Ok(match self {
574            Cache::Redis(e) => e.stream_get_group(key, group)?,
575            Cache::None => return Err("error".to_string()),
576        })
577    }
578
579    pub fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String> {
580        Ok(match self {
581            Cache::Redis(e) => e.stream_get_stream(key)?,
582            Cache::None => return Err("error".to_string()),
583        })
584    }
585}