br_cache/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::collections::HashMap;
use json::{JsonValue, object};
use crate::redis::Redis;


pub mod redis;

#[derive(Clone)]
pub enum Cache {
    Redis(Redis),
    None,
}

impl Cache {
    pub fn new(data: JsonValue) -> Result<Self, String> {
        let res = CacheConfig::from(data);
        let connection = res.connections.get(res.default.as_str()).unwrap().clone();
        let r = Cache::login(connection.mode, &*connection.hostname, &*connection.hostport, &*connection.userpass)?;
        Ok(r)
    }
    /// 登录缓存
    pub fn login(cache_mode: CacheMode, host: &str, port: &str, pass: &str) -> Result<Self, String> {
        let res = match cache_mode {
            CacheMode::Redis => {
                let dsn = if pass.is_empty() {
                    format!("redis://{host}:{port}/")
                } else {
                    format!("redis://:{pass}@{host}:{port}/")
                };
                Cache::Redis(Redis::connect(dsn)?)
            }
        };
        Ok(res)
    }

    pub fn db(&mut self, db: i8) -> &mut Self {
        match self {
            Cache::Redis(e) => {
                e.db(db);
            }
            Cache::None => {}
        }
        self
    }
    /// 设置缓存
    /// * key
    /// * value
    /// * expiration_date 过期时间 秒
    pub fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => e.add(key, value, expiration_date)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }
    pub fn get(&mut self, key: &str) -> Result<JsonValue, String> {
        let res = match self {
            Cache::Redis(e) => e.get(key)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }
    /// 删除缓存
    pub fn delete(&mut self, key: &str) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => e.delete(key)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }

    pub fn exists(&mut self, key: &str) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => e.exists(key)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }

    /// 查询KEY缓存
    pub fn keys(&mut self, key: &str) -> Result<JsonValue, String> {
        let res = match self {
            Cache::Redis(e) => e.keys(key)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }

    /// 集合-添加缓存
    pub fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => e.set_add(key, value)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }
    /// 集合 获取缓存
    pub fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
        let res = match self {
            Cache::Redis(e) => e.set_get(key)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }

    /// 集合 删除缓存
    pub fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => e.set_delete(key, value)?,
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }

    /// 设置消息队列
    fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
        match self {
            Cache::Redis(e) => {
                e.set_message_queue(key, value)
            }
            Cache::None => Err("error".to_string())
        }
    }
    /// 获取消息队列
    pub fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String> {
        match self {
            Cache::Redis(e) => {
                Ok(e.get_message_queue(key)?)
            }
            Cache::None => Err("error".to_string()),
        }
    }
    pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
        let res = match self {
            Cache::Redis(e) => {
                e.set_object(key, field, value)?
            }
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }
    /// 获取哈希值
    pub fn get_object(&mut self, key: &str) -> Result<JsonValue, String> {
        let res = match self {
            Cache::Redis(e) => {
                e.get_object(key)?
            }
            Cache::None => return Err("error".to_string()),
        };
        Ok(res)
    }
}


pub trait CacheBase {
    /// 选择数据库
    fn db(&mut self, db: i8) -> &mut Self;
    /// 设置缓存
    ///
    /// * expiration_date 过期时间 s 秒
    fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String>;
    /// 获取缓存
    fn get(&mut self, key: &str) -> Result<JsonValue, String>;
    /// 删除缓存
    fn delete(&mut self, key: &str) -> Result<bool, String>;
    /// exists 判断KEY是否存在
    /// * key 键
    fn exists(&mut self, key: &str) -> Result<bool, String>;
    /// 查询 KEY
    /// * key 键 格式 * 或 *#### 模糊查询
    fn keys(&mut self, key: &str) -> Result<JsonValue, String>;

    /// 集合 添加
    fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
    /// 集合 获取
    fn set_get(&mut self, key: &str) -> Result<JsonValue, String>;
    /// 集合 删除
    fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
    /// 设置消息队列
    fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
    /// 获取消息队列
    fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String>;
    fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
    /// 获取哈希值
    fn get_object(&mut self, key: &str) -> Result<JsonValue, String>;
}

#[derive(Clone)]
pub struct CacheConfig {
    default: String,
    connections: HashMap<String, Connection>,
}

impl CacheConfig {
    pub fn default() -> CacheConfig {
        let mut connections = HashMap::new();
        connections.insert("my_name".to_string(), Connection::default());
        Self {
            default: "my_name".to_string(),
            connections,
        }
    }
    pub fn json(&mut self) -> JsonValue {
        let mut data = object! {};
        data["default"] = self.default.clone().into();
        let mut connections = object! {};
        for (name, connection) in self.connections.iter_mut() {
            connections[name.clone()] = connection.json().clone();
        }
        data["connections"] = connections;
        data
    }
    pub fn from(data: JsonValue) -> CacheConfig {
        let default = data["default"].to_string();
        let mut connections = HashMap::new();
        for (key, value) in data["connections"].entries() {
            let connection = Connection::default().from(value.clone()).clone();
            connections.insert(key.to_string(), connection.clone());
        }
        Self {
            default,
            connections,
        }
    }
}

#[derive(Clone, Debug)]
struct Connection {
    mode: CacheMode,
    hostname: String,
    hostport: String,
    userpass: String,
}

impl Connection {
    pub fn default() -> Connection {
        Self {
            mode: CacheMode::Redis,
            hostname: "127.0.0.1".to_string(),
            hostport: "6379".to_string(),
            userpass: "".to_string(),
        }
    }
    pub fn json(&mut self) -> JsonValue {
        let mut data = object! {};
        data["mode"] = self.mode.str().into();
        data["hostname"] = self.hostname.clone().into();
        data["hostport"] = self.hostport.clone().into();
        data["userpass"] = self.userpass.clone().into();
        data
    }
    pub fn from(&mut self, data: JsonValue) -> &mut Connection {
        self.mode = CacheMode::from(data["mode"].as_str().unwrap());
        self.hostname = data["hostname"].to_string();
        self.hostport = data["hostport"].to_string();
        self.userpass = data["userpass"].to_string();
        self
    }
}

#[derive(Clone, Debug)]
pub enum CacheMode {
    Redis,
}

impl CacheMode {
    pub fn str(&mut self) -> String {
        match self {
            CacheMode::Redis => "redis"
        }.to_string()
    }
    pub fn from(name: &str) -> Self {
        match name {
            "redis" => CacheMode::Redis,
            _ => CacheMode::Redis
        }
    }
}