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    pub fn create(config_file: PathBuf) -> Config {
258        let data = Config::new();
259        let title = env!("CARGO_PKG_NAME").to_string().replace("-", "_");
260        match fs::read_to_string(config_file.clone()) {
261            Ok(e) => toml::from_str::<Config>(&e).unwrap_or_else(|_| {
262                if e.contains(format!("[{}]", title).as_str()) {
263                    return data;
264                }
265                let toml = toml::to_string(&data).unwrap();
266                let toml = toml.replace("[connections.", format!("[{}.connections.", title).as_str());
267                let toml = format!("[{}]\r\n{}\r\n{}", title, toml, e);
268                let _ = fs::write(config_file.to_str().unwrap(), toml);
269                data
270            }),
271            Err(_) => {
272                fs::create_dir_all(config_file.parent().unwrap()).unwrap();
273                let toml = toml::to_string(&data).unwrap();
274                let toml = toml.replace("[connections.", format!("[{}.connections.", title).as_str());
275                let toml = format!("[{}]\r\n{}\r\n", title, toml);
276                let _ = fs::write(config_file.to_str().unwrap(), toml);
277                data
278            }
279        }
280    }
281    pub fn new() -> Config {
282        let mut connections = BTreeMap::new();
283        connections.insert("my_name".to_string(), Connection::default());
284        Self {
285            default: "my_name".to_string(),
286            connections,
287        }
288    }
289}
290
291#[derive(Clone, Debug, Serialize, Deserialize)]
292pub struct Connection {
293    pub mode: CacheMode,
294    pub hostname: String,
295    pub hostport: String,
296    pub userpass: String,
297}
298impl Default for Connection {
299    fn default() -> Self {
300        Self {
301            mode: CacheMode::Redis,
302            hostname: "127.0.0.1".to_string(),
303            hostport: "6379".to_string(),
304            userpass: "".to_string(),
305        }
306    }
307}
308impl Connection {
309    pub fn from(&mut self, data: JsonValue) -> &mut Connection {
310        self.mode = CacheMode::from(data["mode"].as_str().unwrap());
311        self.hostname = data["hostname"].to_string();
312        self.hostport = data["hostport"].to_string();
313        self.userpass = data["userpass"].to_string();
314        self
315    }
316}
317
318#[derive(Clone, Debug, Serialize, Deserialize)]
319pub enum CacheMode {
320    Redis,
321}
322
323impl CacheMode {
324    pub fn str(&mut self) -> String {
325        match self {
326            CacheMode::Redis => "redis",
327        }.to_string()
328    }
329    pub fn from(name: &str) -> Self {
330        match name {
331            "redis" => CacheMode::Redis,
332            _ => CacheMode::Redis,
333        }
334    }
335}