如何解锁未来的线程和 return 结果
How to unblock a future thread and return results
我决定使用 hyper create 构建一个服务器来读取 POST 方法的主体数据。 解释了我正在寻找的部分内容,但我不想使用 tokio::run
或 future::lazy
因为根据我的理解,hyper 使用 Tokio 和 futures 以及 hyper body return是一个流。我想要完成的是找到其他处理流的方法并获得更多关于 hyper Request
方法的知识。
在第一种方法中,我 concat2
然后调用 wait
。 wait
阻塞当前线程,因此我的代码挂起。
if Method::POST == req.method() {
let body = req.into_body().concat2().wait();
// convert to json and do something with the data.
Ok(Response::new(Body::from("OK: data submitted")))
}
在第二种方法中,我尝试使用 poll
和 and_then
,但我总是得到 NotReady
。结果类型为 futures::poll::Async<hyper::Chunk>
.
if Method::POST == req.method() {
let body = req.into_body().concat2().poll().and_then(|e| {
// do something
Ok(e)
});
match body {
Ok(e) => println!("{:#?}", e),
Err(r) => println!("{:#?}", r),
};
Ok(Response::new(Body::from("")))
}
- 如何解锁当前线程和return结果?
- 我如何进行投票然后 return 结果,?
如果可能,请解释有关如何处理 futures::poll::Async
和 wait()
的良好做法。目前,async
/await
在 Rust 中不稳定,所以我不能使用它。
正如我确定您已经发现的那样,在 futures 上调用 wait()
是一种反模式 并且总体上违背了异步 IO 的目的(因为您重新阻塞你的线程 - 以及执行者 - 这样做)。
hyper
路由接受实现 IntoFuture
的 return,一种为 Option<T>
和 Result<T, E>
实现的类型。因此,您实际编写的内容根本不需要阻塞 - 您只需要像这样组合期货:
if Method::POST == req.method() {
req.into_body().concat2().map(|_body| {
Response::new(Body::from("OK: data submitted"))
})
}
您甚至没有使用 代码中的body
内容,但我假设这是出于 MCVE 目的。在 map()
组合器中,该值当前显示为 _body
并允许你用它做任何你想做的事情。
我猜你是因为文档才发现自己在这个角落的——所有的组合器都在 FutureExt
特征对象上;它们不是在 Future
和 Stream
特征上定义的。因此,在查看 0.2/0.3 文档时它们不会立即浮出水面,因此看起来您唯一可用的调用似乎是 poll_next()
和 wait()
。
我决定使用 hyper create 构建一个服务器来读取 POST 方法的主体数据。 tokio::run
或 future::lazy
因为根据我的理解,hyper 使用 Tokio 和 futures 以及 hyper body return是一个流。我想要完成的是找到其他处理流的方法并获得更多关于 hyper Request
方法的知识。
在第一种方法中,我 concat2
然后调用 wait
。 wait
阻塞当前线程,因此我的代码挂起。
if Method::POST == req.method() {
let body = req.into_body().concat2().wait();
// convert to json and do something with the data.
Ok(Response::new(Body::from("OK: data submitted")))
}
在第二种方法中,我尝试使用 poll
和 and_then
,但我总是得到 NotReady
。结果类型为 futures::poll::Async<hyper::Chunk>
.
if Method::POST == req.method() {
let body = req.into_body().concat2().poll().and_then(|e| {
// do something
Ok(e)
});
match body {
Ok(e) => println!("{:#?}", e),
Err(r) => println!("{:#?}", r),
};
Ok(Response::new(Body::from("")))
}
- 如何解锁当前线程和return结果?
- 我如何进行投票然后 return 结果,?
如果可能,请解释有关如何处理 futures::poll::Async
和 wait()
的良好做法。目前,async
/await
在 Rust 中不稳定,所以我不能使用它。
正如我确定您已经发现的那样,在 futures 上调用 wait()
是一种反模式 并且总体上违背了异步 IO 的目的(因为您重新阻塞你的线程 - 以及执行者 - 这样做)。
hyper
路由接受实现 IntoFuture
的 return,一种为 Option<T>
和 Result<T, E>
实现的类型。因此,您实际编写的内容根本不需要阻塞 - 您只需要像这样组合期货:
if Method::POST == req.method() {
req.into_body().concat2().map(|_body| {
Response::new(Body::from("OK: data submitted"))
})
}
您甚至没有使用 代码中的body
内容,但我假设这是出于 MCVE 目的。在 map()
组合器中,该值当前显示为 _body
并允许你用它做任何你想做的事情。
我猜你是因为文档才发现自己在这个角落的——所有的组合器都在 FutureExt
特征对象上;它们不是在 Future
和 Stream
特征上定义的。因此,在查看 0.2/0.3 文档时它们不会立即浮出水面,因此看起来您唯一可用的调用似乎是 poll_next()
和 wait()
。