br_cache/
lib.rs

1use crate::redis::Redis;
2use json::{object, JsonValue};
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5use std::fs;
6use std::path::PathBuf;
7use std::sync::RwLock;
8use once_cell::sync::Lazy;
9
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 hash_get(&mut self, key: &str) -> Result<JsonValue, String>;
152    /// 添加哈希
153    fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
154    /// 获取哈希指定key的字段值
155    fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String>;
156    /// 获取key下所有的field
157    fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String>;
158    /// 删除哈希指定key的字段
159    fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String>;
160    /// 获取key下所有的value
161    fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String>;
162    /// 地理 添加地理位置
163    fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String>;
164    /// 地理 获取地理位置
165    fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String>;
166    /// 地理 获取两地之间的距离地理位置
167    fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String>;
168    /// 地理 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素
169    fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String>;
170
171    /// 设置消息队列
172    fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String>;
173    /// 获取消息长度
174    fn stream_count(&mut self, key: &str) -> Result<usize, String>;
175    /// 获取 过滤已删除的消息队列
176    fn stream_get(&mut self, key: &str) -> Result<JsonValue, String>;
177    /// 删除消息
178    fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String>;
179
180    /// 创建消费者组
181    fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String>;
182    fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
183    fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
184    /// 删除 消费者
185    fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String>;
186    /// 删除 消费者
187    fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String>;
188    /// 获取组存在不
189    fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String>;
190
191    fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String>;
192}
193
194impl CacheBase for Cache {
195    fn db(&mut self, db: i8) -> &mut Self {
196        match self {
197            Cache::Redis(e) => {
198                e.db(db);
199            }
200            Cache::None => {}
201        }
202        self
203    }
204
205    fn key_exists(&mut self, key: &str) -> Result<bool, String> {
206        Ok(match self {
207            Cache::Redis(e) => e.key_exists(key)?,
208            Cache::None => return Err("error".to_string()),
209        })
210    }
211
212    fn key_del(&mut self, key: &str) -> Result<bool, String> {
213        Ok(match self {
214            Cache::Redis(e) => e.key_del(key)?,
215            Cache::None => return Err("error".to_string()),
216        })
217    }
218
219    fn key_ttl(&mut self, key: &str) -> Result<i64, String> {
220        Ok(match self {
221            Cache::Redis(e) => e.key_ttl(key)?,
222            Cache::None => return Err("error".to_string()),
223        })
224    }
225
226
227    fn key_set_expireat(&mut self, key: &str, timestamp: i64) -> Result<bool, String> {
228        Ok(match self {
229            Cache::Redis(e) => e.key_set_expireat(key, timestamp)?,
230            Cache::None => return Err("error".to_string()),
231        })
232    }
233
234    fn key_set_seconds(&mut self, key: &str, s: i64) -> Result<bool, String> {
235        Ok(match self {
236            Cache::Redis(e) => e.key_set_seconds(key, s)?,
237            Cache::None => return Err("error".to_string()),
238        })
239    }
240
241    fn key_del_expire(&mut self, key: &str) -> Result<bool, String> {
242        Ok(match self {
243            Cache::Redis(e) => e.key_del_expire(key)?,
244            Cache::None => return Err("error".to_string()),
245        })
246    }
247
248    fn key_query(&mut self, key: &str) -> Result<JsonValue, String> {
249        let res = match self {
250            Cache::Redis(e) => e.key_query(key)?,
251            Cache::None => return Err("error".to_string()),
252        };
253        Ok(res)
254    }
255    fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
256        Ok(match self {
257            Cache::Redis(e) => e.add(key, value, expiration_date)?,
258            Cache::None => return Err("error".to_string()),
259        })
260    }
261    fn get(&mut self, key: &str) -> Result<JsonValue, String> {
262        let res = match self {
263            Cache::Redis(e) => e.get(key)?,
264            Cache::None => return Err("error".to_string()),
265        };
266        Ok(res)
267    }
268
269
270    fn set_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
271        let res = match self {
272            Cache::Redis(e) => e.set_add(key, value, expiry_s)?,
273            Cache::None => return Err("error".to_string()),
274        };
275        Ok(res)
276    }
277    fn set_count(&mut self, key: &str) -> Result<usize, String> {
278        let res = match self {
279            Cache::Redis(e) => e.set_count(key)?,
280            Cache::None => return Err("error".to_string()),
281        };
282        Ok(res)
283    }
284    fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
285        let res = match self {
286            Cache::Redis(e) => e.set_get(key)?,
287            Cache::None => return Err("error".to_string()),
288        };
289        Ok(res)
290    }
291
292    fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
293        Ok(match self {
294            Cache::Redis(e) => e.set_delete(key, value)?,
295            Cache::None => return Err("error".to_string()),
296        })
297    }
298
299    fn set_get_sinter(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
300        Ok(match self {
301            Cache::Redis(e) => e.set_get_sinter(keys)?,
302            Cache::None => return Err("error".to_string()),
303        })
304    }
305
306    fn set_get_sunion(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
307        Ok(match self {
308            Cache::Redis(e) => e.set_get_sunion(keys)?,
309            Cache::None => return Err("error".to_string()),
310        })
311    }
312
313    fn list_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
314        Ok(match self {
315            Cache::Redis(e) => e.list_add(key, value, expiry_s)?,
316            Cache::None => return Err("error".to_string()),
317        })
318    }
319
320    fn list_del(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
321        Ok(match self {
322            Cache::Redis(e) => e.list_del(key, value)?,
323            Cache::None => return Err("error".to_string()),
324        })
325    }
326
327
328    /// 哈希 获取
329    fn hash_get(&mut self, key: &str) -> Result<JsonValue, String> {
330        let res = match self {
331            Cache::Redis(e) => e.hash_get(key)?,
332            Cache::None => return Err("error".to_string()),
333        };
334        Ok(res)
335    }
336    /// 哈希 添加
337    fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
338        Ok(match self {
339            Cache::Redis(e) => e.hash_add(key, field, value)?,
340            Cache::None => return Err("error".to_string()),
341        })
342    }
343    fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String> {
344        Ok(match self {
345            Cache::Redis(e) => e.hash_delete(key, field)?,
346            Cache::None => return Err("error".to_string()),
347        })
348    }
349    /// 哈希-获取指定字段的值
350    fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
351        let res = match self {
352            Cache::Redis(e) => e.hash_get_field_value(key, field)?,
353            Cache::None => return Err("error".to_string()),
354        };
355        Ok(res)
356    }
357    /// 哈希-获取所有字段
358    fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String> {
359        Ok(match self {
360            Cache::Redis(e) => e.hash_get_fields(key)?,
361            Cache::None => return Err("error".to_string()),
362        })
363    }
364    /// 哈希-获取所有值
365    fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String> {
366        Ok(match self {
367            Cache::Redis(e) => e.hash_get_values(key)?,
368            Cache::None => return Err("error".to_string()),
369        })
370    }
371
372    fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String> {
373        Ok(match self {
374            Cache::Redis(e) => e.geo_add(key, longitude, latitude, value)?,
375            Cache::None => return Err("error".to_string()),
376        })
377    }
378
379
380    fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String> {
381        Ok(match self {
382            Cache::Redis(e) => e.geo_get(key, value)?,
383            Cache::None => return Err("error".to_string()),
384        })
385    }
386
387    fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String> {
388        Ok(match self {
389            Cache::Redis(e) => e.geo_dist(key, value1, value2)?,
390            Cache::None => return Err("error".to_string()),
391        })
392    }
393
394    fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String> {
395        Ok(match self {
396            Cache::Redis(e) => e.geo_radius(key, value, radius)?,
397            Cache::None => return Err("error".to_string()),
398        })
399    }
400    fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String> {
401        match self {
402            Cache::Redis(e) => e.stream_add(key, msg_id, field, value),
403            Cache::None => Err("error".to_string()),
404        }
405    }
406    fn stream_count(&mut self, key: &str) -> Result<usize, String> {
407        Ok(match self {
408            Cache::Redis(e) => e.stream_count(key)?,
409            Cache::None => return Err("error".to_string()),
410        })
411    }
412
413    fn stream_get(&mut self, key: &str) -> Result<JsonValue, String> {
414        Ok(match self {
415            Cache::Redis(e) => e.stream_get(key)?,
416            Cache::None => return Err("error".to_string()),
417        })
418    }
419
420
421    fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String> {
422        Ok(match self {
423            Cache::Redis(e) => e.stream_group_create(key, group)?,
424            Cache::None => return Err("error".to_string()),
425        })
426    }
427
428    fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String> {
429        Ok(match self {
430            Cache::Redis(e) => e.stream_get_group(key, group)?,
431            Cache::None => return Err("error".to_string()),
432        })
433    }
434
435    fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String> {
436        Ok(match self {
437            Cache::Redis(e) => e.stream_group_del(key, group)?,
438            Cache::None => return Err("error".to_string()),
439        })
440    }
441
442    fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String> {
443        Ok(match self {
444            Cache::Redis(e) => e.stream_del(key, id)?,
445            Cache::None => return Err("error".to_string()),
446        })
447    }
448
449    fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String> {
450        Ok(match self {
451            Cache::Redis(e) => e.stream_get_stream(key)?,
452            Cache::None => return Err("error".to_string()),
453        })
454    }
455
456    fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String> {
457        Ok(match self {
458            Cache::Redis(e) => e.stream_group_msg(key, group, user)?,
459            Cache::None => return Err("error".to_string()),
460        })
461    }
462
463    fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
464        Ok(match self {
465            Cache::Redis(e) => e.stream_group_add_user(key, group, user)?,
466            Cache::None => return Err("error".to_string()),
467        })
468    }
469
470    fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
471        Ok(match self {
472            Cache::Redis(e) => e.stream_group_del_user(key, group, user)?,
473            Cache::None => return Err("error".to_string()),
474        })
475    }
476}
477#[derive(Clone, Debug, Deserialize, Serialize)]
478pub struct Config {
479    pub default: String,
480    pub connections: BTreeMap<String, Connection>,
481}
482
483impl Default for Config {
484    fn default() -> Self {
485        Self::new()
486    }
487}
488
489impl Config {
490    /// 创建配置
491    /// *config_file 配置文件地址
492    /// *path 是否显示包名
493    pub fn create(config_file: PathBuf, pkg_name: bool) -> Config {
494        #[derive(Clone, Debug, Deserialize, Serialize)]
495        pub struct ConfigNew {
496            pub br_cache: Config,
497        }
498        impl ConfigNew {
499            pub fn new() -> ConfigNew {
500                let mut connections = BTreeMap::new();
501                connections.insert("my_name".to_string(), Connection::default());
502                Self {
503                    br_cache: Config {
504                        default: "my_name".to_string(),
505                        connections,
506                    },
507                }
508            }
509        }
510        match fs::read_to_string(config_file.clone()) {
511            Ok(e) => {
512                if pkg_name {
513                    let data = ConfigNew::new();
514                    toml::from_str::<ConfigNew>(&e).unwrap_or_else(|_| {
515                        let toml = toml::to_string(&data).unwrap();
516                        let toml = format!("{e}\r\n{toml}");
517                        let _ = fs::write(config_file.to_str().unwrap(), toml);
518                        data
519                    }).br_cache
520                } else {
521                    Config::new()
522                }
523            }
524            Err(_) => {
525                if pkg_name {
526                    let data = ConfigNew::new();
527                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
528                    let toml = toml::to_string(&data).unwrap();
529                    let _ = fs::write(config_file.to_str().unwrap(), toml);
530                    data.br_cache
531                } else {
532                    let data = Config::new();
533                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
534                    let toml = toml::to_string(&data).unwrap();
535                    let _ = fs::write(config_file.to_str().unwrap(), toml);
536                    data
537                }
538            }
539        }
540    }
541    pub fn new() -> Config {
542        let mut connections = BTreeMap::new();
543        connections.insert("my_name".to_string(), Connection::default());
544        Self {
545            default: "my_name".to_string(),
546            connections,
547        }
548    }
549}
550
551#[derive(Clone, Debug, Serialize, Deserialize)]
552pub struct Connection {
553    pub mode: CacheMode,
554    pub hostname: String,
555    pub hostport: String,
556    pub userpass: String,
557}
558impl Default for Connection {
559    fn default() -> Self {
560        Self {
561            mode: CacheMode::Redis,
562            hostname: "127.0.0.1".to_string(),
563            hostport: "6379".to_string(),
564            userpass: "".to_string(),
565        }
566    }
567}
568impl Connection {
569    pub fn from(data: JsonValue) -> Connection {
570        Self {
571            mode: CacheMode::from(data["mode"].as_str().unwrap_or("")),
572            hostname: data["hostname"].to_string(),
573            hostport: data["hostport"].to_string(),
574            userpass: data["userpass"].to_string(),
575        }
576    }
577    pub fn json(&mut self) -> JsonValue {
578        let mut data = object! {};
579        data["mode"] = self.mode.str().into();
580        data["hostname"] = self.hostname.clone().into();
581        data["hostport"] = self.hostport.clone().into();
582        data["userpass"] = self.userpass.clone().into();
583        data
584    }
585}
586
587#[derive(Clone, Debug, Serialize, Deserialize)]
588pub enum CacheMode {
589    Redis,
590    None,
591}
592
593impl CacheMode {
594    pub fn str(&mut self) -> &'static str {
595        match self {
596            CacheMode::Redis => "redis",
597            CacheMode::None => ""
598        }
599    }
600    pub fn from(name: &str) -> Self {
601        match name {
602            "redis" => CacheMode::Redis,
603            _ => CacheMode::Redis,
604        }
605    }
606}