df-cache 0.1.6

This is an Cache
Documentation
use json::{JsonValue, object};
use log::info;
use redis::{Commands, RedisResult, Connection, Client};


#[derive(Clone)]
pub struct Redis {
    client: Client,
    db: i8,
}
impl Redis {
    pub fn connect(dsn: String) -> Self {
        // 读取配置
        let client = Client::open(dsn);
        match client {
            Ok(client) => {
                return Self {
                    client,
                    db: 0,
                };
            }
            Err(e) => {
                info!("开启错误: {}", e);
                return Self {
                    client: None.unwrap(),
                    db: 0,
                };
            }
        }
    }
    pub fn con(&mut self) -> Connection {
        let mut data = self.client.get_connection().unwrap();
        redis::pipe().cmd("SELECT").arg(self.db).execute(&mut data);
        data
    }
    /// 切换到指定的数据库
    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 {
        let data: RedisResult<bool> = {
            if time > 0 {
                self.con().set_ex(key, value.to_string(), time)
            } else {
                self.con().set(key, value.to_string())
            }
        };
        return match data {
            Ok(_) => {
                true
            }
            Err(e) => {
                info!("{}", e);
                false
            }
        };
    }
    /// 集合 添加
    pub fn set_list(&mut self, key: &str, value: JsonValue) -> bool {
        let data: RedisResult<bool> = self.con().sadd(key, value.to_string());
        return match data {
            Ok(_e) => {
                true
            }
            Err(_e) => {
                false
            }
        };
    }

    /// 删除
    pub fn del(&mut self, key: &str) -> bool {
        let data: RedisResult<bool> = self.con().del(key);
        return match data {
            Ok(_) => {
                true
            }
            Err(e) => {
                info!("{}", e);
                false
            }
        };
    }
    /// 获取
    pub fn get(&mut self, key: &str) -> String {
        let data = self.con().get(key);
        match data {
            Ok(e) => {
                return e;
            }
            Err(_e) => {
                return "".to_string();
            }
        }
    }
    /// 集合 获取
    pub fn get_list(&mut self, key: &str) -> Vec<String> {
        let data: RedisResult<Vec<String>> = self.con().smembers(key);
        self.db = 0;
        match data {
            Ok(e) => {
                return e;
            }
            Err(_e) => {
                return vec![];
            }
        }
    }
    /// 设置消息队列
    pub fn set_message_queue(&mut self, key: &str, value: JsonValue) -> bool {
        let data: RedisResult<String> = self.con().xadd(key, "*", &[(value.to_string(), value.to_string())]);
        match data {
            Ok(e) => {
                info!("{}", e);
                return true;
            }
            Err(e) => {
                info!("{}", e);
                return false;
            }
        }
    }

    /// 消息队列获取
    pub fn get_message_queue(&mut self, key: &str) -> Vec<String> {
        let data = self.con().xread(&[key], &[0]).unwrap();
        data
        // match data {
        //     Ok(e) => {
        //         return vec![];
        //     }
        //     Err(e) => {
        //         println!("{}", e);
        //         return vec![];
        //     }
        // }
    }
    // /// 订阅消息
    // pub fn subscribe_s(&mut self, channel: &str, fun: fn(channel: &str, data: &str)) {
    //     let mut pubsub = self.con.as_pubsub();
    //     pubsub.subscribe(channel).unwrap();
    //     loop {
    //         let msg = pubsub.get_message().unwrap();
    //         // 消息处理
    //         let data: String = msg.get_payload().unwrap();
    //         let channel = msg.get_channel_name();
    //         fun(channel, data.as_str())
    //     }
    // }
    // /// 发布消息
    // pub fn publish(&mut self, key: &str, value: JsonValue) -> bool {
    //     let data = self.con.publish(key, value.to_string());
    //     return match data {
    //         Ok(e) => {
    //             e
    //         }
    //         Err(_e) => {
    //             false
    //         }
    //     };
    // }

    /// 获取对象集合
    pub fn get_object(&mut self, key: &str) -> JsonValue {
        let data: RedisResult<Vec<String>> = self.con().hgetall(key);
        match data {
            Ok(e) => {
                let mut list = object! {};
                let mut index = 0;
                while index < e.len() {
                    list[e[index.clone()].to_string()] = e[index + 1].clone().into();
                    index += 2;
                }
                return list;
            }
            Err(_e) => {
                return object! {};
            }
        }
    }
    /// 设置对象集合
    pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> bool {
        let data: RedisResult<bool> = self.con().hset(key, field, value.to_string());
        return match data {
            Ok(_) => {
                true
            }
            Err(e) => {
                info!("{}", e);
                false
            }
        };
    }
}