From 9dce7d8d57695bd42bc0cdad6dd0f002c67701b8 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 16 Sep 2022 14:27:33 +0200 Subject: [PATCH] tokio-tutorial-mini-redis: Add first client version Uses message passing instead of mutexes. Does not yet send back values from the manager. --- tokio-tutorial-mini-redis/src/bin/client.rs | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tokio-tutorial-mini-redis/src/bin/client.rs 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(); +} -- 2.39.5