异步和同步 API
概述
在本指南中,您可以了解Rust驱动程序的异步和同步API。本指南解释了如何启用可用的API以及如何为每个API结构化代码。
Rust驱动程序支持tokio
异步运行时crate,这是默认运行时。
驱动程序还包括用于需要阻塞或不需要并行处理的用例的同步API。您可以通过在Cargo.toml
文件中添加功能标志来选择同步API。
本指南包括以下部分
配置异步运行时展示了如何配置应用程序以使用
tokio
异步运行时配置同步API展示了如何配置应用程序以使用
sync
和tokio-sync
同步运行时同时使用异步和同步API展示了如何在应用程序中启用异步和同步运行时API
附加信息提供了本指南中提到的类型和方法的相关资源链接和API文档
配置异步运行时
驱动程序默认使用 tokio
运行时,因此您可以在项目的 Cargo.toml
文件中不指定任何功能标志来使用此运行时。有关安装驱动程序和配置 Cargo.toml
文件的更多信息,请参阅下载和安装 的快速入门步骤。
重要
从 Rust 驱动程序 v3.0 开始,tokio
运行时是驱动程序支持的唯一异步运行时包。驱动程序的前版本也支持 async-std
运行时包。
如果您的应用程序使用 async-std
运行时,您可以通过创建一个 Runtime
结构体实例,并使用 Runtime::spawn()
方法将驱动程序操作包装起来,在同一个应用程序中启动一个 tokio
运行时。请确保您使用相同的 Runtime
实例来实例化一个 Client
并在 Client
实例上调用驱动程序方法。
有关创建 Runtime
并调用 spawn()
方法的示例,请参阅 tokio 文档。
Tokio 运行时示例
以下代码使用 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).await }); }
配置同步API
驱动程序还提供了一种阻塞、同步API。要使用 tokio
同步API,请将 "sync"
特性标志添加到 mongodb
依赖项中,如下例所示
[dependencies.mongodb] version = "3.1.0" features = ["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); } }
同时使用异步和同步API
您可以在同一应用程序中使用异步和同步API。例如,为了启用两个 tokio
运行时,您可以将 tokio
依赖项添加到您的依赖项列表中,并将 "sync"
标志添加到 mongodb
依赖项中
[dependencies] futures = "0.3.28" tokio = {version = "1.32.0", features = ["full"]} [dependencies.mongodb] version = "3.1.0" features = ["sync"]
附加信息
有关本指南中概念的更多信息,请参阅以下页面
API文档
有关本指南中提到的方法和类型的更多信息,请参阅以下API文档