Rust常用库之MongoDB Rust Driver(Rust操作MongoDB )

本文介绍了Rust MongoDB RustDriver库的使用,特别关注了如何避免超时/取消问题,提倡正确轮询driver返回的future,以确保API的稳定性和一致性。示例代码演示了如何在异步Rust中安全地与MongoDB交互并设置超时机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rust常用库之MongoDB Rust Driver(Rust操作MongoDB )

MongoDB Rust Driver
官网: https://mongodb.github.io/mongo-rust-driver/manual/
crates: https://crates.io/crates/https://crates.io/crates/mongodb

介绍

mongodb是官方支持的 MongoDB Rust 驱动程序的手册,这是一个客户端库,可用于与 Rust 应用程序中的 MongoDB 进行交互。它使用 bson crate 来支持 BSON。驱动程序包含一个完全异步的 API,它支持 tokio (默认)或 async-std, 具体取决于设置的功能标志。驱动程序还有一个同步 API,可以通过功能标志启用。

关于超时/取消的警告

In async Rust, it is common to implement cancellation and timeouts by dropping a future after a certain period of time instead of polling it to completion. This is how tokio::time::timeout works, for example. However, doing this with futures returned by the driver can leave the driver’s internals in an inconsistent state, which may lead to unpredictable or incorrect behavior (see RUST-937 for more details). As such, it is highly recommended to poll all futures returned from the driver to completion. In order to still use timeout mechanisms like tokio::time::timeout with the driver, one option is to spawn tasks and time out on their JoinHandle futures instead of on the driver’s futures directly. This will ensure the driver’s futures will always be completely polled while also allowing the application to continue in the event of a timeout.

在异步 Rust 中,通常通过在一段时间后丢弃而不是轮询它来实现取消和超时。

因此,强烈建议轮询从驱动程序完成返回。

e.g.

#![allow(unused)]
fn main() {
extern crate mongodb;
extern crate tokio;
use std::time::Duration;
use mongodb::{
    Client,
    bson::doc,
};

async fn foo() -> std::result::Result<(), Box<dyn std::error::Error>> {

let client = Client::with_uri_str("mongodb://example.com").await?;
let collection = client.database("foo").collection("bar");
let handle = tokio::task::spawn(async move {
    collection.insert_one(doc! { "x": 1 }, None).await
});

tokio::time::timeout(Duration::from_secs(5), handle).await???;
Ok(())
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西京刀客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值