use tokio::runtime::Handle; // 1.0.2
use poem::{
get, handler, listener::TcpListener, middleware::Tracing, web::Path, EndpointExt, Route, Server,
};
fn inner_example(handle: Handle) -> String {
let resp = futures::executor::block_on(async {
handle
.spawn(async {
// Do work here
reqwest::get("https://www.rust-lang.org")
.await
.unwrap()
.text()
.await
.unwrap()
})
.await
.expect("Task spawned in Tokio executor panicked")
});
resp
}
#[handler]
fn hello(Path(name): Path<String>) -> String {
inner_example(Handle::current())
}
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let app = Route::new().at("/hello/:name", get(hello)).with(Tracing);
Server::new(TcpListener::bind("0.0.0.0:3000"))
.name("hello-world")
.run(app)
.await
}
在此程序中,reqwest请求从未被调用,程序将挂起。
我按照https://stackoverflow.com/a/62536772/13208393的说明进行操作,但在这种情况下不起作用。
的说明
您没有遵循该帖子的说明。这篇文章使用
spawn_blocking
从非异步工作线程执行 block_on
(std::thread::spawn
是另一个选项)。
您没有这样做,您是直接从运行时工作线程运行
block_on
,因此您使运行时陷入僵局。
另外...如果您想从其中调用
reqwest
,为什么要使用同步处理程序?只需使用 async
处理程序并使 inner_example
异步。你无缘无故地制造了你不知道如何解决的问题。