为什么 futures::executor::block_on 挂在诗歌处理程序中

问题描述 投票:0回答:1
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的说明进行操作,但在这种情况下不起作用。

multithreading rust rust-tokio rust-poem
1个回答
0
投票

我遵循了https://stackoverflow.com/a/62536772/13208393

的说明

没有遵循该帖子的说明。这篇文章使用

spawn_blocking
从非异步工作线程执行
block_on
std::thread::spawn
是另一个选项)。

您没有这样做,您是直接从运行时工作线程运行

block_on
,因此您使运行时陷入僵局。

另外...如果您想从其中调用

reqwest
,为什么要使用同步处理程序?只需使用
async
处理程序并使
inner_example
异步。你无缘无故地制造了你不知道如何解决的问题。

© www.soinside.com 2019 - 2024. All rights reserved.