From 1c7b4ef0160e6bb52fae703d6cbb8dfab89cbc07 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 16 Sep 2022 14:42:09 +0200 Subject: [PATCH] tokio-tutorial-mini-redis: Show return value in client Use an oneshot message sender to deliver the result. --- tokio-tutorial-mini-redis/src/bin/client.rs | 22 ++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/tokio-tutorial-mini-redis/src/bin/client.rs b/tokio-tutorial-mini-redis/src/bin/client.rs index e7ec116..184170e 100644 --- a/tokio-tutorial-mini-redis/src/bin/client.rs +++ b/tokio-tutorial-mini-redis/src/bin/client.rs @@ -1,15 +1,21 @@ use bytes::Bytes; use mini_redis::client; -use tokio::sync::mpsc; +use tokio::sync::{ mpsc, oneshot }; + +/// Provided by the requester and used by the manager task to send +/// the command response back to the requester. +type Responder = oneshot::Sender>; #[derive(Debug)] enum Command { Get { key: String, + resp: Responder>, }, Set { key: String, val: Bytes, + resp: Responder<()>, } } @@ -23,8 +29,8 @@ async fn main() { 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(); } + Command::Get { key, resp } => { resp.send(client.get(&key).await).unwrap(); } + Command::Set { key, val, resp } => { resp.send(client.set(&key, val).await).unwrap(); } } } }); @@ -32,11 +38,17 @@ async fn main() { 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 (resp_tx, resp_rx) = oneshot::channel(); + manager_tx.send(Command::Get { key: "hello".to_string(), resp: resp_tx }).await.unwrap(); + let res = resp_rx.await; + println!("t1: got {:?}", res); }); let t2 = tokio::spawn(async move { - manager_tx2.send(Command::Set { key: "hello".to_string(), val: "bar".into() }).await.unwrap(); + let (resp_tx, resp_rx) = oneshot::channel(); + manager_tx2.send(Command::Set { key: "hello".to_string(), val: "bar".into(), resp: resp_tx }).await.unwrap(); + let res = resp_rx.await.unwrap(); + println!("t2: got {:?}", res); }); t1.await.unwrap(); -- 2.39.5