在python中使用motor库进行高并发异步mongodb操作,核心在于利用`asyncio`事件循环与motor提供的非阻塞api。你需要通过`motor.motor_asyncio.asynciomotorclient`创建客户端,并在协程中调用数据库和集合方法。由于motor基于pymongo,其底层连接池管理是线程安全的,但在异步上下文中,必须确保所有数据库操作都在`await`语句中执行,以避免阻塞事件循环。

如何正确初始化Motor客户端并建立连接?
正确初始化Motor客户端的关键是使用`AsyncIOMotorClient`而非同步的`MongoClient`。你需要传入MongoDB的连接URI,并可选地设置最大连接数等参数。初始化后,客户端不会立即建立物理连接,而是在第一次操作时进行握手。为了在高并发场景下保持连接稳定,建议复用同一个客户端实例,而不是为每个请求创建新实例。

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
# 定义连接字符串
MONGO_URI = "mongodb://localhost:27017/"
DATABASE_NAME = "test_db"
COLLECTION_NAME = "users"
async def main():
# 1. 初始化异步客户端
client = AsyncIOMotorClient(MONGO_URI, maxPoolSize=50)
# 2. 获取数据库和集合引用
db = client[DATABASE_NAME]
collection = db[COLLECTION_NAME]
# 3. 验证连接 (ping)
try:
await client.admin.command('ping')
print("Connected successfully")
except Exception as e:
print(f"Connection failed: {e}")
finally:
# 4. 关闭连接
client.close()
if __name__ == "__main__":
asyncio.run(main())
如何在高并发场景下执行批量插入或查询?
在高并发场景下,执行批量操作时应避免在循环中逐个`await`单个文档操作,因为这会串行化执行,降低吞吐量。对于插入操作,可以使用`insert_many`并配合`ordered=False`以提高速度;对于查询,应使用游标(Cursor)并迭代处理。更重要的是,使用`asyncio.gather`或`asyncio.TaskGroup`(Python 3.11+)来并发执行多个独立的数据库操作,从而充分利用异步优势。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
MONGO_URI = "mongodb://localhost:27017/"
DB_NAME = "test_db"
COLL_NAME = "logs"
async def insert_log(collection, log_data):
"""模拟插入一条日志"""
return await collection.insert_one(log_data)
async def query_logs(collection, limit=10):
"""模拟查询最近日志"""
cursor = collection.find().sort("timestamp", -1).limit(limit)
return await cursor.to_list(length=limit)
async def main():
client = AsyncIOMotorClient(MONGO_URI)
collection = client[DB_NAME][COLL_NAME]
# 准备并发数据
tasks = []
for i in range(100):
task = insert_log(collection, {"msg": f"Log {i}", "ts": i})
tasks.append(task)
# 并发执行所有插入任务
results = await asyncio.gather(*tasks)
print(f"Inserted {len(results)} documents concurrently.")
# 并发执行查询
query_task = asyncio.create_task(query_logs(collection))
await query_task
client.close()
if __name__ == "__main__":
asyncio.run(main())
如何处理Motor中的异常以确保高可用?
在高并发异步操作中,网络抖动或MongoDB瞬时不可用可能导致`ServerSelectionTimeoutError`或`OperationFailure`。为了确保系统的高可用性,必须在每个关键的数据库操作周围包裹`try-except`块。捕获异常后,不应直接抛出,而应记录日志并根据业务逻辑决定是重试、降级还是返回默认值。此外,使用指数退避策略进行重试可以有效应对瞬态故障,避免对数据库造成冲击。
import asyncio
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import ServerSelectionTimeoutError, OperationFailure
logging.basicConfig(level=logging.INFO)
async def safe_insert(collection, document, max_retries=3):
for attempt in range(max_retries):
try:
result = await collection.insert_one(document)
return result.inserted_id
except (ServerSelectionTimeoutError, OperationFailure) as e:
logging.warning(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
await asyncio.sleep(2 ** attempt) # 指数退避
else:
logging.error("Max retries reached. Insert failed.")
raise
async def main():
client = AsyncIOMotorClient("mongodb://localhost:27017/")
coll = client.test_db.test_coll
try:
doc_id = await safe_insert(coll, {"status": "ok"})
print(f"Document inserted with ID: {doc_id}")
except Exception as e:
print(f"Failed to insert: {e}")
finally:
client.close()
if __name__ == "__main__":
asyncio.run(main())

















