]> piware.de Git - learn-rust.git/blob - tokio-tutorial-mini-redis/src/bin/client.rs
tokio-tutorial-mini-redis: Add first client version
[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;
4
5 #[derive(Debug)]
6 enum Command {
7     Get {
8         key: String,
9     },
10     Set {
11         key: String,
12         val: Bytes,
13     }
14 }
15
16 #[tokio::main]
17 async fn main() {
18     let (manager_tx, mut manager_rx) = mpsc::channel(32);
19
20     let manager = tokio::spawn(async move {
21         // Establish a connection to the server
22         let mut client = client::connect("127.0.0.1:6379").await.unwrap();
23
24         while let Some(cmd) = manager_rx.recv().await {
25             match cmd {
26                 Command::Get { key } => { client.get(&key).await.unwrap(); }
27                 Command::Set { key, val } => { client.set(&key, val).await.unwrap(); }
28             }
29         }
30     });
31
32     let manager_tx2 = manager_tx.clone();
33     // Spawn two tasks, one gets a key, the other sets a key
34     let t1 = tokio::spawn(async move {
35         manager_tx.send(Command::Get { key: "hello".to_string() }).await.unwrap();
36     });
37
38     let t2 = tokio::spawn(async move {
39         manager_tx2.send(Command::Set { key: "hello".to_string(), val: "bar".into() }).await.unwrap();
40     });
41
42     t1.await.unwrap();
43     t2.await.unwrap();
44     manager.await.unwrap();
45 }