使用 mongodb-1.2.2 和 Rocket-0.5.0-rc.1 会导致异步运行时不兼容

问题描述

背景资料

嘿,我正在努力建立一个带有 rocket 数据库的 mongodb rest api。

我已经能够成功创建到 MongoDB Atlas 的连接,并通过 rocket 构建器函数将生成的客户端放入 manage 的状态管理中,如下所示:

#[launch]
async fn rocket() -> _ {
    let client = database::connect::pool(1,32).await.unwrap();

    rocket::build()
        .mount("/",routes!(routes::index))
        .manage(database::rocket::ClientPointer(client))
}

使用此代码,我没有收到任何启动错误,仅作为旁注。

实际问题

实际问题来自于消耗客户端状态并获取所有数据库的异步路由。

#[get("/")]
pub async fn index(client: &State<ClientPointer>) -> &'static str {
    let _dbs = client.0.list_databases(None,None).await.unwrap();

    "Fetched databases"
}

调用此路由时,控制台会打印以下输出:

>> Matched: (index) GET /
thread 'rocket-worker-thread' panicked at 'there is no timer running,must be called from the context of a Tokio 0.2.x runtime',C:\Users\lukasdiegelmann\.cargo\registry\src\github.com-1ecc6299db9ec823\tokio-0.2.25\src\time\driver\handle.rs:24:32
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
   >> Handler index panicked.
   >> This is an application bug.
   >> A panic in Rust must be treated as an exceptional event.
   >> Panicking is not a suitable error handling mechanism.
   >> Unwinding,the result of a panic,is an expensive operation.
   >> Panics will severely degrade application performance.
   >> Instead of panicking,return `Option` and/or `Result`.
   >> Values of either type can be returned directly from handlers.
   >> A panic is treated as an internal server error.
   >> Outcome: Failure
   >> No 500 catcher registered. Using Rocket default.
   >> Response succeeded.

因此,使用的异步运行时的版本控制似乎有问题。但我找不到在哪里,因为错误并没有真正给我一个提示,而且 mongodb rust 驱动程序似乎正在使用 0.2.x 版本的 tokio,即版本 ~0.2.18

依赖项

以下是 Cargo.toml 文件中的所有依赖项:

[dependencies]
rocket = "0.5.0-rc.1"
dotenv = "0.15.0"
mongodb = "1.2.2"

[dependencies.openssl]
version = "0.10"
features = ["vendored"]

更新

所以,我获得了更多的洞察力,似乎 rocket 版本 0.5.0-rc.1 终于开始使用 tokio 1.x 异步运行时,而 {{1 }} mongodb 没有。

这显然带来了一个大问题,因为我要么必须同时运行两个运行时,要么暂时放弃 mongodb,这并不完全是解决方案的定义...

解决方案

MongoDB 已发布其驱动程序的测试版,该版本使用 1.2.2 tokio 异步运行时。

here

解决方法

这已经解决了。解决方法见上文。它标有说明解决方案的标题。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...