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();
  6. // Start receiving messages
  7. while let Some(cmd) = rx.recv().await {
  8. use Command::*;
  9. match cmd {
  10. Get { key } => {
  11. client.get(&key).await;
  12. }
  13. Set { key, val } => {
  14. client.set(&key, val).await;
  15. }
  16. }
  17. }
  18. });

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();
  4. // Spawn two tasks, one gets a key, the other sets a key
  5. let t1 = tokio::spawn(async move {
  6. let cmd = Command::Get {
  7. key: "hello".to_string(),
  8. };
  9. tx.send(cmd).await.unwrap();
  10. });
  11. let t2 = tokio::spawn(async move {
  12. let cmd = Command::Set {
  13. key: "foo".to_string(),
  14. val: "bar".into(),
  15. };
  16. tx2.send(cmd).await.unwrap();
  17. });

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();