我正在尝试编写一个tokio事件循环,该循环可以执行来自同一服务器的具有以下特征的获取请求:
到目前为止,在我的尝试中,我设法使这4个项目的组合有所不同,但从未组合在一起。我的主要问题是我不太了解如何将新的期货添加到tokio事件循环中。
我假设我需要对轮询接收方的主循环使用loop_fn
,并使用handle.spawn
来产生新任务? handle.spawn
仅允许Result<(),()>
的期货,因此我无法使用其输出来在失败时重新生成作业,因此我需要将重试支票移到该期货中?
下面是一次尝试以批量方式接收和处理url(因此没有连续轮询),并且超时(但没有重试):
fn place_dls(&mut self, reqs: Vec<String>) {
let mut core = Core::new().unwrap();
let handle = core.handle();
let timeout = Timeout::new(Duration::from_millis(5000), &handle).unwrap();
let send_dls = stream::iter_ok::<_, reqwest::Error>(reqs.iter().map(|o| {
// send with request through an async reqwest client in self
}));
let rec_dls = send_dls.buffer_unordered(dls.len()).for_each(|n| {
n.into_body().concat2().and_then(|full_body| {
debug!("Received: {:#?}", full_body);
// TODO: how to put the download back in the queue if failure code is received?
})
});
let work = rec_dls.select2(timeout).then(|res| match res {
Ok(Either::A((got, _timeout))) => {
Ok(got)
},
Ok(Either::B((_timeout_error, _get))) => {
// TODO: put back in queue
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Client timed out while connecting",
).into())
}
Err(Either::A((get_error, _timeout))) => Err(get_error.into()),
Err(Either::B((timeout_error, _get))) => Err(timeout_error.into()),
});
core.run(work);
}
我尝试使用loop_fn
失败了。
答案 0 :(得分:1)
我假设我需要在主循环中使用loop_fn
我会建议另一种方法:实现futures::sync::mpsc::Receiver
流使用者而不是循环。
它可以看作是一种主过程:通过Receiver
接收到URL后,可以产生一个tokio任务来下载内容。这样,重试就不会有问题:只需将失败或超时的url通过其Sender
端点再次发送到主通道。
这是一个工作代码草图:
extern crate futures;
extern crate tokio;
use std::{io, time::{Duration, Instant}};
use futures::{
Sink,
Stream,
stream,
sync::mpsc,
future::Future,
};
use tokio::{
runtime::Runtime,
timer::{Delay, Timeout},
};
fn main() -> Result<(), io::Error> {
let mut rt = Runtime::new()?;
let executor = rt.executor();
let (tx, rx) = mpsc::channel(0);
let master_tx = tx.clone();
let master = rx.for_each(move |url: String| {
let download_future = download(&url)
.map(|_download_contents| {
// TODO: actually do smth with contents
()
});
let timeout_future =
Timeout::new(download_future, Duration::from_millis(2000));
let job_tx = master_tx.clone();
let task = timeout_future
.or_else(move |error| {
// actually download error or timeout, retry
println!("retrying {} because of {:?}", url, error);
job_tx.send(url).map(|_| ()).map_err(|_| ())
});
executor.spawn(task);
Ok(())
});
rt.spawn(master);
let urls = vec![
"http://url1".to_string(),
"http://url2".to_string(),
"http://url3".to_string(),
];
rt.executor()
.spawn(tx.send_all(stream::iter_ok(urls)).map(|_| ()).map_err(|_| ()));
rt.shutdown_on_idle().wait()
.map_err(|()| io::Error::new(io::ErrorKind::Other, "shutdown failure"))
}
#[derive(Debug)]
struct DownloadContents;
#[derive(Debug)]
struct DownloadError;
fn download(url: &str) -> Box<Future<Item = DownloadContents, Error = DownloadError> + Send> {
// TODO: actually download here
match url {
// url2 always fails
"http://url2" => {
println!("FAILED downloading: {}", url);
let future = Delay::new(Instant::now() + Duration::from_millis(1000))
.map_err(|_| DownloadError)
.and_then(|()| Err(DownloadError));
Box::new(future)
},
// url3 always timeouts
"http://url3" => {
println!("TIMEOUT downloading: {}", url);
let future = Delay::new(Instant::now() + Duration::from_millis(5000))
.map_err(|_| DownloadError)
.and_then(|()| Ok(DownloadContents));
Box::new(future)
},
// everything else succeeds
_ => {
println!("SUCCESS downloading: {}", url);
let future = Delay::new(Instant::now() + Duration::from_millis(50))
.map_err(|_| DownloadError)
.and_then(|()| Ok(DownloadContents));
Box::new(future)
},
}
}