Create the channel
In the main
function, an mpsc
channel is created.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
// Create a new channel with a capacity of at most 32.
let (tx, mut rx) = mpsc::channel(32);
// ... Rest comes here
}
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:
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(32);
let tx2 = tx.clone();
tokio::spawn(async move {
tx.send("sending from first handle").await;
});
tokio::spawn(async move {
tx2.send("sending from second handle").await;
});
while let Some(message) = rx.recv().await {
println!("GOT = {}", message);
}
}
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.