From: Martin Pitt Date: Fri, 16 Sep 2022 12:27:33 +0000 (+0200) Subject: tokio-tutorial-mini-redis: Add first client version X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=9dce7d8d57695bd42bc0cdad6dd0f002c67701b8 tokio-tutorial-mini-redis: Add first client version Uses message passing instead of mutexes. Does not yet send back values from the manager. --- diff --git a/tokio-tutorial-mini-redis/src/bin/client.rs b/tokio-tutorial-mini-redis/src/bin/client.rs new file mode 100644 index 0000000..e7ec116 --- /dev/null +++ b/tokio-tutorial-mini-redis/src/bin/client.rs @@ -0,0 +1,45 @@ +use bytes::Bytes; +use mini_redis::client; +use tokio::sync::mpsc; + +#[derive(Debug)] +enum Command { + Get { + key: String, + }, + Set { + key: String, + val: Bytes, + } +} + +#[tokio::main] +async fn main() { + let (manager_tx, mut manager_rx) = mpsc::channel(32); + + let manager = tokio::spawn(async move { + // Establish a connection to the server + let mut client = client::connect("127.0.0.1:6379").await.unwrap(); + + while let Some(cmd) = manager_rx.recv().await { + match cmd { + Command::Get { key } => { client.get(&key).await.unwrap(); } + Command::Set { key, val } => { client.set(&key, val).await.unwrap(); } + } + } + }); + + let manager_tx2 = manager_tx.clone(); + // Spawn two tasks, one gets a key, the other sets a key + let t1 = tokio::spawn(async move { + manager_tx.send(Command::Get { key: "hello".to_string() }).await.unwrap(); + }); + + let t2 = tokio::spawn(async move { + manager_tx2.send(Command::Set { key: "hello".to_string(), val: "bar".into() }).await.unwrap(); + }); + + t1.await.unwrap(); + t2.await.unwrap(); + manager.await.unwrap(); +}