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

use json::JsonValue;
use crate::mode::mode::Mode;
use crate::mode::redis::Redis;

pub struct Cache {
    mode: Mode,
    db: i8,
}

impl Cache {
    pub fn connect(config: JsonValue) -> Self {
        if config.is_empty() {
            return Self {
                mode: Mode::None,
                db: 0,
            };
        }
        let connections = config["connections"].clone();
        let default = config["default"].to_string();
        let connection = connections[default.clone()].clone();
        let mode = match connection["mode"].as_str().unwrap() {
            "redis" => {
                let dsn = {
                    if connection["userpass"] != "" {
                        format!("redis://:{}@{}:{}/", connection["userpass"], connection["hostname"], connection["hostport"])
                    } else {
                        format!("redis://{}:{}/", connection["hostname"], connection["hostport"])
                    }
                };
                Mode::Redis(Redis::connect(dsn.clone()))
            }
            _ => {
                let dsn = {
                    if connection["userpass"] != "" {
                        format!("redis://:{}@{}:{}/", connection["userpass"], connection["hostname"], connection["hostport"])
                    } else {
                        format!("redis://{}:{}/", connection["hostname"], connection["hostport"])
                    }
                };
                Mode::Redis(Redis::connect(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)
    }

    /// 设置列表缓存
    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)
    }
}