我正在尝试使用FuturesOrdered
发送并行异步Rusoto SQS请求:
use futures::prelude::*; // 0.1.26
use futures::stream::futures_unordered::FuturesUnordered;
use rusoto_core::{Region, HttpClient}; // 0.38.0
use rusoto_credential::EnvironmentProvider; // 0.17.0
use rusoto_sqs::{SendMessageBatchRequest, SendMessageBatchRequestEntry, Sqs, SqsClient}; // 0.38.0
fn main() {
let client = SqsClient::new_with(
HttpClient::new().unwrap(),
EnvironmentProvider::default(),
Region::UsWest2,
);
let messages: Vec<u32> = (1..12).map(|n| n).collect();
let chunks: Vec<_> = messages.chunks(10).collect();
let tasks: FuturesUnordered<_> = chunks.into_iter().map(|c| {
let batch = create_batch(c);
client.send_message_batch(batch)
}).collect();
let tasks = tasks
.for_each(|t| {
println!("{:?}", t);
Ok(())
})
.map_err(|e| println!("{}", e));
tokio::run(tasks);
}
fn create_batch(ids: &[u32]) -> SendMessageBatchRequest {
let queue_url = "https://sqs.us-west-2.amazonaws.com/xxx/xxx".to_string();
let entries = ids
.iter()
.map(|id| SendMessageBatchRequestEntry {
id: id.to_string(),
message_body: id.to_string(),
..Default::default()
})
.collect();
SendMessageBatchRequest {
entries,
queue_url,
}
}
任务正确完成,但是tokio::run(tasks)
不会停止。我认为是因为tasks.for_each()
会迫使它继续运行并寻找更多的期货吗?
tokio::run(tasks)
为什么不停止?我是否正确使用FuturesOrdered
?
当创建多达60,000张期货并将其推入FuturesUnordered
组合器时,我还担心内存使用情况。
答案 0 :(得分:0)
我发现是由于主要功能中的SqsClient
导致其阻塞,因为即使任务已完成,它仍在做一些内部工作。
Rusoto的一个人提供的解决方案是将其添加到tokio::run
std::mem::drop(client);