]> piware.de Git - learn-rust.git/blob - tokio-tutorial-mini-redis/src/bin/client.rs
tokio-tutorial-mini-redis: Show return value in client
[learn-rust.git] / tokio-tutorial-mini-redis / src / bin / client.rs
1 use bytes::Bytes;
2 use mini_redis::client;
3 use tokio::sync::{ mpsc, oneshot };
4
5 /// Provided by the requester and used by the manager task to send
6 /// the command response back to the requester.
7 type Responder<T> = oneshot::Sender<mini_redis::Result<T>>;
8
9 #[derive(Debug)]
10 enum Command {
11     Get {
12         key: String,
13         resp: Responder<Option<Bytes>>,
14     },
15     Set {
16         key: String,
17         val: Bytes,
18         resp: Responder<()>,
19     }
20 }
21
22 #[tokio::main]
23 async fn main() {
24     let (manager_tx, mut manager_rx) = mpsc::channel(32);
25
26     let manager = tokio::spawn(async move {
27         // Establish a connection to the server
28         let mut client = client::connect("127.0.0.1:6379").await.unwrap();
29
30         while let Some(cmd) = manager_rx.recv().await {
31             match cmd {
32                 Command::Get { key, resp } => { resp.send(client.get(&key).await).unwrap(); }
33                 Command::Set { key, val, resp } => { resp.send(client.set(&key, val).await).unwrap(); }
34             }
35         }
36     });
37
38     let manager_tx2 = manager_tx.clone();
39     // Spawn two tasks, one gets a key, the other sets a key
40     let t1 = tokio::spawn(async move {
41         let (resp_tx, resp_rx) = oneshot::channel();
42         manager_tx.send(Command::Get { key: "hello".to_string(), resp: resp_tx }).await.unwrap();
43         let res = resp_rx.await;
44         println!("t1: got {:?}", res);
45     });
46
47     let t2 = tokio::spawn(async move {
48         let (resp_tx, resp_rx) = oneshot::channel();
49         manager_tx2.send(Command::Set { key: "hello".to_string(), val: "bar".into(), resp: resp_tx }).await.unwrap();
50         let res = resp_rx.await.unwrap();
51         println!("t2: got {:?}", res);
52     });
53
54     t1.await.unwrap();
55     t2.await.unwrap();
56     manager.await.unwrap();
57 }