【问题标题】:'rocket-worker-thread' panicked at 'Cannot drop a runtime in a context where blocking is not allowed''rocket-worker-thread' 在'不能在不允许阻塞的上下文中删除运行时'时惊慌失措
【发布时间】:2021-11-23 06:08:57
【问题描述】:

我正在尝试调用下游 API 并将结果作为 Json 对象返回。我正在使用reqwest,它使用tokio

Cargo.toml

[dependencies]
rocket = { version = "0.5.0-rc.1", features = ["secrets", "tls", "json"] }
reqwest = { version = "0.11", features = ["blocking", "json"] }
tokio = { version = "1", features = ["full"] }

main.rs

#[post("/teams")]
fn teams() -> Json<Vec<Team>> {
    let mut r = reqwest::blocking::get("https://example.com");
    if r.is_ok() {
        return Json(get_teams(r.unwrap().text().unwrap()));
    } else {
        return Json(Vec::new());
    }
}

我得到的错误是:

thread 'rocket-worker-thread' panicked at 'Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an asynchronous context.'

这是因为我使用了阻塞调用吗?如何进行阻塞调用并简单地返回结果。任何指导将不胜感激。

【问题讨论】:

  • 用tokio为什么还要用blocking?!?
  • 这个问题你解决了吗?@Nightwolf
  • @Dolphin 是的,我发布了答案

标签: rust rust-tokio rust-rocket reqwest


【解决方案1】:

这是为我做的:

#[post("/teams")]
async fn teams() -> Json<Vec<Team>> {
    return Json(get_teams(reqwest::get("https://example.com").await.unwrap().text().await.unwrap()));
}

Cargo.toml

reqwest = { version = "0.11", features = ["blocking", "json"] }
tokio = { version = "1", features = ["full"] }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多