br_cache/
lib.rs

1use crate::redis::Redis;
2use json::{JsonValue};
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5use std::fs;
6use std::path::PathBuf;
7
8pub mod redis;
9
10#[derive(Clone)]
11pub enum Cache {
12    Redis(Redis),
13    None,
14}
15
16impl Cache {
17    pub fn new(config: Config) -> Result<Self, String> {
18        let connection = config.connections.get(config.default.as_str()).unwrap().clone();
19        Cache::login(
20            connection.mode,
21            &connection.hostname,
22            &connection.hostport,
23            &connection.userpass,
24        )
25    }
26    /// 登录缓存
27    pub fn login(
28        cache_mode: CacheMode,
29        host: &str,
30        port: &str,
31        pass: &str,
32    ) -> Result<Self, String> {
33        let res = match cache_mode {
34            CacheMode::Redis => {
35                let dsn = if pass.is_empty() {
36                    format!("redis://{host}:{port}/")
37                } else {
38                    format!("redis://:{pass}@{host}:{port}/")
39                };
40                Cache::Redis(Redis::connect(dsn)?)
41            }
42        };
43        Ok(res)
44    }
45
46    pub fn db(&mut self, db: i8) -> &mut Self {
47        match self {
48            Cache::Redis(e) => {
49                e.db(db);
50            }
51            Cache::None => {}
52        }
53        self
54    }
55    /// 设置缓存
56    /// * key
57    /// * value
58    /// * expiration_date 过期时间 秒
59    pub fn add(
60        &mut self,
61        key: &str,
62        value: JsonValue,
63        expiration_date: u64,
64    ) -> Result<bool, String> {
65        let res = match self {
66            Cache::Redis(e) => e.add(key, value, expiration_date)?,
67            Cache::None => return Err("error".to_string()),
68        };
69        Ok(res)
70    }
71    pub fn get(&mut self, key: &str) -> Result<JsonValue, String> {
72        let res = match self {
73            Cache::Redis(e) => e.get(key)?,
74            Cache::None => return Err("error".to_string()),
75        };
76        Ok(res)
77    }
78    /// 删除缓存
79    pub fn delete(&mut self, key: &str) -> Result<bool, String> {
80        let res = match self {
81            Cache::Redis(e) => e.delete(key)?,
82            Cache::None => return Err("error".to_string()),
83        };
84        Ok(res)
85    }
86
87    pub fn exists(&mut self, key: &str) -> Result<bool, String> {
88        let res = match self {
89            Cache::Redis(e) => e.exists(key)?,
90            Cache::None => return Err("error".to_string()),
91        };
92        Ok(res)
93    }
94
95    /// 查询KEY缓存
96    pub fn keys(&mut self, key: &str) -> Result<JsonValue, String> {
97        let res = match self {
98            Cache::Redis(e) => e.keys(key)?,
99            Cache::None => return Err("error".to_string()),
100        };
101        Ok(res)
102    }
103
104    /// 集合-添加缓存
105    pub fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
106        let res = match self {
107            Cache::Redis(e) => e.set_add(key, value)?,
108            Cache::None => return Err("error".to_string()),
109        };
110        Ok(res)
111    }
112    /// 集合 获取缓存
113    pub fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
114        let res = match self {
115            Cache::Redis(e) => e.set_get(key)?,
116            Cache::None => return Err("error".to_string()),
117        };
118        Ok(res)
119    }
120
121    /// 集合 删除缓存
122    pub fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
123        let res = match self {
124            Cache::Redis(e) => e.set_delete(key, value)?,
125            Cache::None => return Err("error".to_string()),
126        };
127        Ok(res)
128    }
129
130    /// 设置消息队列
131    pub fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
132        match self {
133            Cache::Redis(e) => e.set_message_queue(key, value),
134            Cache::None => Err("error".to_string()),
135        }
136    }
137    /// 获取消息队列
138    pub fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String> {
139        match self {
140            Cache::Redis(e) => Ok(e.get_message_queue(key)?),
141            Cache::None => Err("error".to_string()),
142        }
143    }
144    pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
145        let res = match self {
146            Cache::Redis(e) => e.set_object(key, field, value)?,
147            Cache::None => return Err("error".to_string()),
148        };
149        Ok(res)
150    }
151    /// 获取哈希值
152    pub fn get_object(&mut self, key: &str) -> Result<JsonValue, String> {
153        let res = match self {
154            Cache::Redis(e) => e.get_object(key)?,
155            Cache::None => return Err("error".to_string()),
156        };
157        Ok(res)
158    }
159    /// 哈希-添加
160    pub fn add_hash(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
161        let res = match self {
162            Cache::Redis(e) => e.add_hash(key, field, value)?,
163            Cache::None => return Err("error".to_string()),
164        };
165        Ok(res)
166    }
167    /// 哈希-删除
168    pub fn delete_hash(&mut self, key: &str, field: &str) -> Result<bool, String> {
169        let res = match self {
170            Cache::Redis(e) => e.delete_hash(key, field)?,
171            Cache::None => return Err("error".to_string()),
172        };
173        Ok(res)
174    }
175    /// 哈希-获取指定字段的值
176    pub fn get_hash_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
177        let res = match self {
178            Cache::Redis(e) => e.get_hash_field_value(key, field)?,
179            Cache::None => return Err("error".to_string()),
180        };
181        Ok(res)
182    }
183    /// 哈希-获取所有字段
184    pub fn get_hash_fields(&mut self, key: &str) -> Result<JsonValue, String> {
185        let res = match self {
186            Cache::Redis(e) => e.get_hash_fields(key)?,
187            Cache::None => return Err("error".to_string()),
188        };
189        Ok(res)
190    }
191    /// 哈希-获取所有值
192    pub fn get_hash_values(&mut self, key: &str) -> Result<JsonValue, String> {
193        let res = match self {
194            Cache::Redis(e) => e.get_hash_values(key)?,
195            Cache::None => return Err("error".to_string()),
196        };
197        Ok(res)
198    }
199}
200
201pub trait CacheBase {
202    /// 选择数据库
203    fn db(&mut self, db: i8) -> &mut Self;
204    /// 设置缓存
205    ///
206    /// * expiration_date 过期时间 s 秒
207    fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String>;
208    /// 获取缓存
209    fn get(&mut self, key: &str) -> Result<JsonValue, String>;
210    /// 删除缓存
211    fn delete(&mut self, key: &str) -> Result<bool, String>;
212    /// exists 判断KEY是否存在
213    /// * key 键
214    fn exists(&mut self, key: &str) -> Result<bool, String>;
215    /// 查询 KEY
216    /// * key 键 格式 * 或 *#### 模糊查询
217    fn keys(&mut self, key: &str) -> Result<JsonValue, String>;
218
219    /// 集合 添加
220    fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
221    /// 集合 获取
222    fn set_get(&mut self, key: &str) -> Result<JsonValue, String>;
223    /// 集合 删除
224    fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
225    /// 设置消息队列
226    fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
227    /// 获取消息队列
228    fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String>;
229    fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
230    /// 获取哈希值
231    fn get_object(&mut self, key: &str) -> Result<JsonValue, String>;
232    /// 添加哈希
233    fn add_hash(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
234    /// 获取哈希指定key的字段值
235    fn get_hash_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String>;
236    /// 获取key下所有的field
237    fn get_hash_fields(&mut self, key: &str) -> Result<JsonValue, String>;
238    /// 删除哈希指定key的字段
239    fn delete_hash(&mut self, key: &str, field: &str) -> Result<bool, String>;
240    /// 获取key下所有的value
241    fn get_hash_values(&mut self, key: &str) -> Result<JsonValue, String>;
242}
243
244#[derive(Clone, Debug, Deserialize, Serialize)]
245pub struct Config {
246    pub default: String,
247    pub connections: BTreeMap<String, Connection>,
248}
249
250impl Default for Config {
251    fn default() -> Self {
252        Self::new()
253    }
254}
255
256impl Config {
257    /// 创建配置
258    /// *config_file 配置文件地址
259    /// *path 是否显示包名
260    pub fn create(config_file: PathBuf, pkg_name: bool) -> Config {
261        #[derive(Clone, Debug, Deserialize, Serialize)]
262        pub struct ConfigNew {
263            pub br_cache: Config,
264        }
265        impl ConfigNew {
266            pub fn new() -> ConfigNew {
267                let mut connections = BTreeMap::new();
268                connections.insert("my_name".to_string(), Connection::default());
269                Self {
270                    br_cache: Config {
271                        default: "my_name".to_string(),
272                        connections,
273                    },
274                }
275            }
276        }
277        match fs::read_to_string(config_file.clone()) {
278            Ok(e) => {
279                if pkg_name {
280                    let data = ConfigNew::new();
281                    toml::from_str::<ConfigNew>(&e).unwrap_or_else(|_| {
282                        let toml = toml::to_string(&data).unwrap();
283                        let toml = format!("{}\r\n{}", e, toml);
284                        let _ = fs::write(config_file.to_str().unwrap(), toml);
285                        data
286                    }).br_cache
287                } else {
288                    Config::new()
289                }
290            }
291            Err(_) => {
292                if pkg_name {
293                    let data = ConfigNew::new();
294                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
295                    let toml = toml::to_string(&data).unwrap();
296                    let _ = fs::write(config_file.to_str().unwrap(), toml);
297                    data.br_cache
298                } else {
299                    let data = Config::new();
300                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
301                    let toml = toml::to_string(&data).unwrap();
302                    let _ = fs::write(config_file.to_str().unwrap(), toml);
303                    data
304                }
305            }
306        }
307    }
308    pub fn new() -> Config {
309        let mut connections = BTreeMap::new();
310        connections.insert("my_name".to_string(), Connection::default());
311        Self {
312            default: "my_name".to_string(),
313            connections,
314        }
315    }
316}
317
318#[derive(Clone, Debug, Serialize, Deserialize)]
319pub struct Connection {
320    pub mode: CacheMode,
321    pub hostname: String,
322    pub hostport: String,
323    pub userpass: String,
324}
325impl Default for Connection {
326    fn default() -> Self {
327        Self {
328            mode: CacheMode::Redis,
329            hostname: "127.0.0.1".to_string(),
330            hostport: "6379".to_string(),
331            userpass: "".to_string(),
332        }
333    }
334}
335impl Connection {
336    pub fn from(&mut self, data: JsonValue) -> &mut Connection {
337        self.mode = CacheMode::from(data["mode"].as_str().unwrap());
338        self.hostname = data["hostname"].to_string();
339        self.hostport = data["hostport"].to_string();
340        self.userpass = data["userpass"].to_string();
341        self
342    }
343}
344
345#[derive(Clone, Debug, Serialize, Deserialize)]
346pub enum CacheMode {
347    Redis,
348}
349
350impl CacheMode {
351    pub fn str(&mut self) -> String {
352        match self {
353            CacheMode::Redis => "redis",
354        }.to_string()
355    }
356    pub fn from(name: &str) -> Self {
357        match name {
358            "redis" => CacheMode::Redis,
359            _ => CacheMode::Redis,
360        }
361    }
362}