Spawn manager task

Next, spawn a task that processes messages from the channel. First, a client connection is established to Redis. Then, received commands are issued via the Redis connection.

1. use mini_redis::client;
2. // The `move` keyword is used to **move** ownership of `rx` into the task.
3. let manager = tokio::spawn(async move {
4. // Establish a connection to the server
5. let mut client = client::connect("127.0.0.1:6379").await.unwrap();

7. // Start receiving messages
8. while let Some(cmd) = rx.recv().await {
9. use Command::*;

11. match cmd {
12. Get { key } => {
13. client.get(&key).await;
14. }
15. Set { key, val } => {
16. client.set(&key, val).await;
17. }
18. }
19. }
20. });

Now, update the two tasks to send commands over the channel instead of issuing them directly on the Redis connection.

1. // The `Sender` handles are moved into the tasks. As there are two
2. // tasks, we need a second `Sender`.
3. let tx2 = tx.clone();

5. // Spawn two tasks, one gets a key, the other sets a key
6. let t1 = tokio::spawn(async move {
7. let cmd = Command::Get {
8. key: "hello".to_string(),
9. };

11. tx.send(cmd).await.unwrap();
12. });

14. let t2 = tokio::spawn(async move {
15. let cmd = Command::Set {
16. key: "foo".to_string(),
17. val: "bar".into(),
18. };

20. tx2.send(cmd).await.unwrap();
21. });

At the bottom of the main function, we .await the join handles to ensure the commands fully complete before the process exits.

1. t1.await.unwrap();
2. t2.await.unwrap();
3. manager.await.unwrap();