【发布时间】:2021-08-29 06:05:55
【问题描述】:
背景资料
嘿,我正在努力建立一个带有 mongodb 数据库的 rocket rest api。
我已经能够成功地创建到MongoDB Atlas 的连接,并通过manage 构建器函数将生成的客户端放入rocket 的状态管理中,如下所示:
#[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 异步运行时,而 mongodb 1.2.2 还没有。
这显然带来了一个大问题,因为我要么必须同时运行两个运行时,要么暂时放弃 mongodb,这不完全是解决方案的定义......
解决方案
MongoDB 已发布其驱动程序的测试版,它使用 tokio 1.x 异步运行时。
【问题讨论】:
标签: mongodb rust rust-rocket tokio