Overview
在本指南中,您可以学习;了解如何优化Rust驾驶员的性能。要连接到MongoDB,您必须创建一个 Client实例。您的 Client实例会自动处理连接的大多数方面,例如发现服务器拓扑结构和监控连接。本指南介绍了配置和使用 Client实例的最佳实践。
本指南包括以下部分:
其他信息提供了指向本指南中提及的类型和方法的资源和API文档的链接。
客户端生命周期
我们建议您在会话和操作中重复使用客户端。 您可以使用同一Client实例来执行多个任务,因为Client类型可以安全地由多个线程并发使用。 为每个请求创建新的Client实例会导致性能下降。
以下代码创建一个接受指向现有Client实例的指针的方法,该实例允许您使用同一客户端执行多个请求:
// ... Create a client earlier in your code async fn make_request(client: &Client) -> Result<(), Box<dyn Error>> { // Use the client to perform operations Ok(()) }
并行度
您可以通过运行异步并发任务来执行并行数据操作来优化性能。以下示例使用 tokio::task 模块中的 spawn() 方法创建单独的并发任务来执行插入操作:
let client = Client::with_uri_str("<connection string>").await?; let data = doc! { "title": "1984", "author": "George Orwell" }; for i in 0..5 { let client_ref = client.clone(); let data_ref = data.clone(); task::spawn(async move { let collection = client_ref .database("items") .collection::<Document>(&format!("coll{}", i)); collection.insert_one(data_ref).await }); }
运行时
Client实例绑定到您在其中创建它的tokio或async-std运行时的实例。 如果使用Client实例在不同的运行时上执行操作,则可能会遇到意外行为或故障。
如果使用 tokio 或 async_std 包中的 test 辅助宏来测试应用程序,则可能会无意中在与 Client实例预期不同的运行时中运行操作。发生这种情况是因为这些辅助宏为每个测试创建了新的运行时。您可以使用以下策略之一来避免此问题:
将运行时附加到
Client实例,而不使用test辅助宏。为每个
async测试创建一个新的Client实例。
以下示例将全局运行时附加到 Client实例以进行测试。 test_list_dbs() 方法使用连接到此运行时的客户端列出部署中的数据库:
use tokio::runtime::Runtime; use once_cell::sync::Lazy; static CLIENT_RUNTIME: Lazy<(Client, Runtime)> = Lazy::new(|| { let rt = Runtime::new().unwrap(); let client = rt.block_on(async { Client::with_uri_str("<connection string>").await.unwrap() }); (client, rt) }); fn test_list_dbs() -> Result<(), Box<dyn Error>> { let (client, rt) = &*CLIENT_RUNTIME; rt.block_on(async { client.list_database_names().await })?; Ok(()) }
以下示例使用 tokio::test 为每次测试运行创建一个新的 Client实例,确保运行时之间不会出现意外的交互:
async fn test_list_dbs() -> Result<(), Box<dyn Error>> { let client = Client::with_uri_str("<connection string>").await?; client.list_database_names().await?; Ok(()) }
更多信息
要学习;了解有关连接到MongoDB 的更多信息,请参阅创建MongoDB客户端指南。
要学习;了解有关Rust驾驶员可用运行时的更多信息,请参阅异步和同步 API指南。
要学习;了解如何使用连接池优化性能,请参阅《使用连接池管理连接》指南。
API 文档
模块中的spawn()
tokio::tasktokio::runtime module