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
mod mode;

use std::collections::HashMap;
use std::fs;
use json::{JsonValue, object};
use crate::mode::mode::Mode;
use crate::mode::redis::Redis;

#[derive(Clone)]
pub struct Cache {
    mode: Mode,
    db: i8,
}

impl Cache {
    pub fn load(path: &str) -> Self {
        let config = match fs::read_to_string(path.clone()) {
            Ok(e) => {
                match json::parse(e.as_str()) {
                    Ok(e) => e,
                    Err(_) => {
                        let mut res = CacheConfig::default();
                        fs::write(path, res.json().to_string()).unwrap();
                        res.json()
                    }
                }
            }
            Err(_) => {
                let mut res = CacheConfig::default();
                fs::write(path, res.json().to_string()).unwrap();
                res.json()
            }
        };
        Cache::connect(config)
    }
    pub fn connect(config: JsonValue) -> Self {
        let config = CacheConfig::from(config);
        let connection = config.connections.get(&*config.default).clone().unwrap().clone();
        let mode = match connection.mode {
            Modes::Redis => {
                Mode::Redis(Redis::connect(connection.get_dsn().clone()))
            }
        };
        Self {
            mode,
            db: 0,
        }
    }
    /// 选择数据库
    pub fn db(&mut self, db: i8) -> &mut Self {
        self.db = db;
        self
    }
    /// 设置缓存
    ///
    /// * time 过期时间 s 秒
    pub fn set(&mut self, key: &str, value: JsonValue, time: usize) -> bool {
        self.mode.set(self.db, key, value, time)
    }
    /// 获取缓存
    pub fn get(&mut self, key: &str) -> JsonValue {
        self.mode.get(self.db, key)
    }
    /// 删除缓存
    pub fn del(&mut self, key: &str) -> bool {
        self.mode.del(self.db, key)
    }

    /// 查询KEY缓存
    pub fn keys(&mut self, key: &str) -> JsonValue {
        self.mode.keys(self.db, key)
    }

    /// 设置列表缓存
    pub fn set_list(&mut self, key: &str, value: JsonValue) -> bool {
        self.mode.set_list(self.db, key, value)
    }
    /// 获取列表缓存
    pub fn get_list(&mut self, key: &str) -> JsonValue {
        self.mode.get_list(self.db, key)
    }

    /// 设置消息队列
    pub fn set_message_queue(&mut self, key: &str, value: JsonValue) -> bool {
        self.mode.set_message_queue(self.db, key, value)
    }
    /// 获取消息队列
    pub fn get_message_queue(&mut self, key: &str) -> JsonValue {
        self.mode.get_message_queue(self.db, key)
    }
    pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> bool {
        self.mode.set_object(self.db, key, field, value)
    }
    /// 获取哈希值
    pub fn get_object(&mut self, key: &str) -> JsonValue {
        self.mode.get_object(self.db, key)
    }
}

#[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)]
struct Connection {
    mode: Modes,
    hostname: String,
    hostport: String,
    userpass: String,
}

impl Connection {
    pub fn default() -> Connection {
        Self {
            mode: Modes::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 = Modes::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
    }
    pub fn get_dsn(self) -> String {
        match self.mode {
            Modes::Redis => {
                if self.userpass != "" {
                    format!("redis://:{}@{}:{}/", self.userpass, self.hostname, self.hostport)
                } else {
                    format!("redis://{}:{}/", self.hostname, self.hostport)
                }
            }
        }
    }
}

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

impl Modes {
    pub fn str(&mut self) -> &'static str {
        match self {
            Modes::Redis => "redis"
        }
    }
    pub fn from(name: &str) -> Self {
        match name {
            "redis" => Modes::Redis,
            _ => Modes::Redis
        }
    }
}