br_cache/
lib.rs

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