use json::JsonValue;
use redis as pro_redis;
use redis::{Commands, RedisResult};
pub struct Redis {
con: pro_redis::Connection,
db: i8,
}
impl Redis {
pub fn connect(dsn: String) -> Self {
let client = pro_redis::Client::open(dsn).unwrap();
let con = client.get_connection();
match con {
Ok(e) => {
return Self { con: e, db: 0 };
}
Err(e) => {
println!("缓存连接错误:{}", e);
return Self {
con: None.unwrap(),
db: 0,
};
}
}
}
pub fn db(&mut self, db: i8) -> &mut Self {
self.db = db;
pro_redis::pipe().cmd("SELECT").arg(self.db).execute(&mut self.con);
self
}
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) => {
println!("{}", 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) => {
println!("{}", 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) => {
println!("{}", e);
return true;
}
Err(e) => {
println!("{}", e);
return false;
}
}
}
pub fn get_message_queue(&mut self, key: &str) -> Vec<String> {
let data = self.con.xread(&[key], &[0]).unwrap();
data
}
}