Skip to content

Commit

Permalink
single connection type redis client logic completed.
Browse files Browse the repository at this point in the history
  • Loading branch information
fuyoo committed Jul 10, 2024
1 parent e04e2d9 commit 0ee41b0
Show file tree
Hide file tree
Showing 7 changed files with 128 additions and 45 deletions.
5 changes: 3 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ window-shadows = "0.2.2"
log = { version = "0.4.21", features = [] }
tauri-plugin-shell = "2.0.0-beta.7"
redis = { version = "0.25.4", features = ["tokio-comp"] }
anyhow = "1.0.86"

[features]
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
Expand Down
17 changes: 1 addition & 16 deletions src-tauri/src/api/defines.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,3 @@
use serde::{Deserialize, Serialize};
use crate::api::rdb::Rdb;

#[derive(Serialize, Deserialize, Debug)]
pub struct ConnectionInfo{
pub host: String,
pub port: Option<String>,
pub db: Option<String>,
pub username: Option<String>,
pub password: Option<String>
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ConnectionImpl {
pub id: usize,
pub name: String,
pub node: Vec<ConnectionInfo>,
pub cluster: Option<bool>
}
38 changes: 13 additions & 25 deletions src-tauri/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,20 @@
pub mod defines;
mod rdb;
pub mod rdb;
pub mod resp;

use log::error;
use serde::Serialize;
use redis::cmd;
use tauri::command;
use resp::Response;
use crate::r_ok;
use crate::api::rdb::RedisClientImpl;

pub trait IntoResponse {
fn into_response(self) -> String;
}

#[derive(Serialize, Debug)]
pub struct Response {}

impl Response {
pub fn into_response(self) -> String {
serde_json::to_string(&self).unwrap_or_else(|e| {
error!("{:?}", e);
String::from("{}")
})
}
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[command]
pub async fn request(rid: &str, action: &str, connection_info: rdb::ConnectionImpl, data: &str) -> tauri::Result<Response<Option<String>>> {
println!("rid: {}\naction: {}\nconnection_info: {:?}\ndata: {:?}", rid, action, connection_info, data);
let r = connection_info.into_client().unwrap().do_command::<Option<String>>(&cmd("get").arg("123"))?;
println!("{:#?}", r);
Ok(r_ok!(r, None))
}


// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[command]
pub fn request(rid: &str, action: &str, connection_info: defines::ConnectionImpl, data: &str) -> String {
println!("rid: {}\naction: {}\nconnection_info: {:?}\ndata: {}", rid,action,connection_info, data);

let resp = Response {};
resp.into_response()
}
61 changes: 60 additions & 1 deletion src-tauri/src/api/rdb.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,63 @@
pub struct Rdb {}
use redis::{Client, Cmd, FromRedisValue};
use serde::{Deserialize, Serialize};

// connection info
#[derive(Serialize, Deserialize, Debug)]
pub struct ConnectionInfo {
pub host: String,
pub port: Option<String>,
pub db: Option<String>,
pub username: Option<String>,
pub password: Option<String>,
}

// connection impl
#[derive(Serialize, Deserialize, Debug)]
pub struct ConnectionImpl {
pub id: usize,
pub name: String,
pub node: Vec<ConnectionInfo>,
pub cluster: Option<bool>,
}

impl ConnectionImpl {
pub fn into_client(self) -> anyhow::Result<impl RedisClientImpl> {
if self.cluster.is_none() {
let cfg = &self.node[0];
RedisSingleClient::connect(cfg)
} else {
// 这里等下一步去实现
todo!()
}
}
}


pub trait RedisClientImpl {
fn do_command<T: FromRedisValue>(self, cmd: &Cmd) -> anyhow::Result<T>;
}

pub struct RedisSingleClient(Client);

impl RedisClientImpl for RedisSingleClient {
fn do_command<T: FromRedisValue>(self, cmd: &Cmd) -> anyhow::Result<T> {
let mut conn = self.0.get_connection()?;
return Ok(cmd.query::<T>(&mut conn)?);
}
}
impl RedisSingleClient {
pub fn connect(cfg: &ConnectionInfo) -> anyhow::Result<RedisSingleClient> {
let c = Client::open(format!(
"redis://{}:{}@{}:{}/{}?timeout=3s",
cfg.username.clone().unwrap_or("".to_string()),
cfg.password.clone().unwrap_or("".to_string()),
cfg.host,
cfg.port.clone().unwrap_or("6379".to_string()),
cfg.db.clone().unwrap_or("0".to_string())
))?;
Ok(RedisSingleClient(c))
}

}


50 changes: 50 additions & 0 deletions src-tauri/src/api/resp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use std::error::Error;
use serde::Serialize;

#[derive(Serialize, Debug)]
pub struct Response<T> where T: serde::Serialize {
pub code: i32,
pub data: T,
pub msg: Option<String>,
}

#[macro_export] macro_rules! r_ok {
($data: expr,$msg:expr) => {
Response {
code: 0,
data:$data,
msg:$msg,
}
}
}
#[macro_export] macro_rules! r_fail {
($msg:expr) => {
Response {
code: 3,
data: (),
msg:$msg,
}
}
}
#[macro_export] macro_rules! r_error {
($err:expr) => {
Response {
code: 5,
data:(),
msg:Some(format!("{:?}",$err)),
}
}
}
impl<T: serde::Serialize> Response<T> {
pub fn ok(data: T, msg: Option<String>) -> Response<T> {
r_ok!(data,msg)
}

pub fn fail(msg: Option<String>) -> Response<()> {
r_fail!(msg)
}

pub fn error(err: impl Error) -> Response<()> {
r_error!(err)
}
}
1 change: 0 additions & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]


fn main() {
bsrdc::run();
}

0 comments on commit 0ee41b0

Please sign in to comment.