Create the channel

In the main function, an mpsc channel is created.

  1. use tokio::sync::mpsc;
  2. #[tokio::main]
  3. async fn main() {
  4. // Create a new channel with a capacity of at most 32.
  5. let (tx, mut rx) = mpsc::channel(32);
  6. // ... Rest comes here
  7. }

The mpsc channel is used to send commands to the task managing the redis connection. The multi-producer capability allows messages to be sent from many tasks. Creating the channel returns two values, a sender and a receiver. The two handles are used separately. They may be moved to different tasks.

The channel is created with a capacity of 32. If messages are sent faster than they are received, the channel will store them. Once the 32 messages are stored in the channel, calling send(...).await will go to sleep until a message has been removed by the receiver.

Sending from multiple tasks is done by cloning the Sender. For example:

  1. use tokio::sync::mpsc;
  2. #[tokio::main]
  3. async fn main() {
  4. let (tx, mut rx) = mpsc::channel(32);
  5. let tx2 = tx.clone();
  6. tokio::spawn(async move {
  7. tx.send("sending from first handle").await;
  8. });
  9. tokio::spawn(async move {
  10. tx2.send("sending from second handle").await;
  11. });
  12. while let Some(message) = rx.recv().await {
  13. println!("GOT = {}", message);
  14. }
  15. }

Both messages are sent to the single Receiver handle. It is not possible to clone the receiver of an mpsc channel.

When every Sender has gone out of scope or has otherwise been dropped, it is no longer possible to send more messages into the channel. At this point, the recv call on the Receiver will return None, which means that all senders are gone and the channel is closed.

In our case of a task that manages the Redis connection, it knows that it can close the Redis connection once the channel is closed, as the connection will not be used again.