Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/

异步和同步 API

在本指南中,您可以了解 Rust 驱动程序的异步同步API。 本指南介绍了如何启用可用的 API 并构建代码以使用每个 API。

Rust 驱动程序支持 tokioasync-std ,这是两个流行的异步运行时 crate。 默认情况下,驱动程序使用tokio异步运行时,但您可以通过将功能标志添加到Cargo.toml文件中的mongodb依赖项来选择特定的运行时。

该驱动程序还包括一个同步 API,适用于需要阻塞或不需要并行的使用案例。 您可以通过将功能标志添加到Cargo.toml文件中的mongodb依赖项来选择同步 API。

驱动程序默认使用tokio运行时。 您可以通过将"tokio-runtime""async-std-runtime"功能标志添加到mongodb依赖项中来显式选择运行时。

从以下标签页中进行选择,查看如何为每个相应的 crate 添加功能标志:

[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-runtime"]
[dependencies.mongodb]
version = "2.8.2"
default-features = false
features = ["async-std"]

有关安装驾驶员和添加功能标志的详细信息,请参阅快速入门的下载和安装步骤。

以下代码使用tokio包中的task模块为多个数据操作创建单独的并发任务:

let client = Client::with_uri_str("<connection string>").await?;
let some_data = doc! { "title": "1984", "author": "George Orwell" };
for i in 0..5 {
let client_ref = client.clone();
let somedata_ref = some_data.clone();
task::spawn(async move {
let collection = client_ref
.database("items")
.collection::<Document>(&format!("coll{}", i));
collection.insert_one(somedata_ref, None).await
});
}

该驱动程序还提供阻塞、同步 API。 要使用同步 API,请将"sync""tokio-sync"功能标志添加到mongodb依赖项中。

从以下标签页中进行选择,查看如何为每个相应的 crate 添加功能标志:

[dependencies.mongodb]
version = "2.8.2"
default-features = false
features = ["sync"]
[dependencies.mongodb]
version = "2.8.2"
default-features = false
features = ["tokio-sync"]

使用同步 API 时,请使用mongodb::sync模块中的类型来执行操作。 以下代码使用sync模块通过同步 API 将数据插入到集合中。 当insert_one方法在for循环内运行时,驱动程序会等待每个请求完成后再继续。

use mongodb::sync::Client;
fn main() {
let client = Client::with_uri_str("<connection string>")?;
let some_data = doc! { "title": "1984", "author": "George Orwell" };
for i in 0..5 {
let client_ref = client.clone();
let somedata_ref = some_data.clone();
let collection = client_ref
.database("items")
.collection::<Document>(&format!("coll{}", i));
collection.insert_one(somedata_ref, None);
}
}

您可以在同一应用程序中同时使用异步和同步 API。 例如,要启用两个tokio运行时,可以将tokio依赖项添加到依赖项列表中,并将"tokio-sync"标志添加到mongodb依赖项中:

[dependencies]
futures = "0.3.28"
tokio = {version = "1.32.0", features = ["full"]}
[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-sync"]

有关本指南中概念的更多信息,请参阅以下页面:

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

后退

性能考虑因素

在此页面上