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
}
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
}
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
}
};
}
}