背景资料
嘿,我正在努力建立一个rocket
带有mongodb
数据库的休息 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 版本,即 version ~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
异步运行时的驱动程序的 beta 版本。