在异步 Rust (Tokio) 中包装阻塞 mpsc
Wrapping blocking mpsc in async Rust (Tokio)
我正在尝试使用 Tokio 包装同步 MQTT 客户端 library。该代码需要通过 std::sync::mpsc
通道不断接收消息并将它们发送到异步代码中。我了解如何使用 spawn_blocking
包装 returns 单个值的代码。但这如何应用于包装一个不断从 std::sync::mpsc
频道接收消息的循环?
这是我用来向频道发送消息的代码。
let (mut tx, mut rx) = std::sync::mpsc::channel();
tokio::spawn(async move {
let mut mqtt_options = MqttOptions::new("bot", settings.mqtt.host, settings.mqtt.port);
let (mut mqtt_client, notifications) = MqttClient::start(mqtt_options).unwrap();
mqtt_client.subscribe(settings.mqtt.topic_name, QoS::AtLeastOnce).unwrap();
tokio::task::spawn_blocking(move || {
println!("Waiting for notifications");
for notification in notifications {
match notification {
rumqtt::Notification::Publish(publish) => {
let payload = Arc::try_unwrap(publish.payload).unwrap();
let text: String = String::from_utf8(payload).expect("Can't decode payload for notification");
println!("Recieved message: {}", text);
let msg: Message = serde_json::from_str(&text).expect("Error while deserializing message");
println!("Deserialized message: {:?}", msg);
println!("{}", msg);
tx.send(msg);
}
_ => println!("{:?}", notification)
}
}
});
});
但我不确定我应该如何使用 tokio API 在另一个异步闭包中接收这些消息。
tokio::task::spawn(async move || {
// How to revieve messages via `rx` here? I can't use tokio::sync::mpsc channels
// since the code that sends messages is blocking.
});
我已经发布了 separate thread on a rust-lang community 并在那里得到了答案。
std::sync::mpsc::channel
可以换成 tokio::sync::mpsc::unbounded_channel
,它有一个非异步发送方法。它解决了这个问题。
我正在尝试使用 Tokio 包装同步 MQTT 客户端 library。该代码需要通过 std::sync::mpsc
通道不断接收消息并将它们发送到异步代码中。我了解如何使用 spawn_blocking
包装 returns 单个值的代码。但这如何应用于包装一个不断从 std::sync::mpsc
频道接收消息的循环?
这是我用来向频道发送消息的代码。
let (mut tx, mut rx) = std::sync::mpsc::channel();
tokio::spawn(async move {
let mut mqtt_options = MqttOptions::new("bot", settings.mqtt.host, settings.mqtt.port);
let (mut mqtt_client, notifications) = MqttClient::start(mqtt_options).unwrap();
mqtt_client.subscribe(settings.mqtt.topic_name, QoS::AtLeastOnce).unwrap();
tokio::task::spawn_blocking(move || {
println!("Waiting for notifications");
for notification in notifications {
match notification {
rumqtt::Notification::Publish(publish) => {
let payload = Arc::try_unwrap(publish.payload).unwrap();
let text: String = String::from_utf8(payload).expect("Can't decode payload for notification");
println!("Recieved message: {}", text);
let msg: Message = serde_json::from_str(&text).expect("Error while deserializing message");
println!("Deserialized message: {:?}", msg);
println!("{}", msg);
tx.send(msg);
}
_ => println!("{:?}", notification)
}
}
});
});
但我不确定我应该如何使用 tokio API 在另一个异步闭包中接收这些消息。
tokio::task::spawn(async move || {
// How to revieve messages via `rx` here? I can't use tokio::sync::mpsc channels
// since the code that sends messages is blocking.
});
我已经发布了 separate thread on a rust-lang community 并在那里得到了答案。
std::sync::mpsc::channel
可以换成 tokio::sync::mpsc::unbounded_channel
,它有一个非异步发送方法。它解决了这个问题。