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

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(())
}
}

猜你喜欢

转载自blog.csdn.net/inthat/article/details/125791918