为什么是MongoDB';s的python motor客户端在使用starlette运行时比pymongo慢得多?
我有一个用python和异步框架Starlette()编写的web应用程序,我需要连接到MongoDB,所以我安装了异步pymongo驱动程序:motor()版本2.1.0 我有一些类似这样的伪代码:为什么是MongoDB';s的python motor客户端在使用starlette运行时比pymongo慢得多?,mongodb,pymongo,python-asyncio,Mongodb,Pymongo,Python Asyncio,我有一个用python和异步框架Starlette()编写的web应用程序,我需要连接到MongoDB,所以我安装了异步pymongo驱动程序:motor()版本2.1.0 我有一些类似这样的伪代码: motor_client = motor.motor_asyncio.AsyncIOMotorClient(...) pymongo_client = pymongo.MongoClient(...) class BlogList(HTTPEndpoint): async def ge
motor_client = motor.motor_asyncio.AsyncIOMotorClient(...)
pymongo_client = pymongo.MongoClient(...)
class BlogList(HTTPEndpoint):
async def get(self, request):
blog_list = [item async for item in motor_client.blog.find(condition)]
# blog_list = list(pymongo_client.blog.find(condition))
data = {
"request": request,
"blogs": blog_list,
}
return RenderPageResponse("index.html", data)
对于这里的blog\u列表
行,我使用wrk-t10-d10-c100对其进行了基准测试http://localhost:8080/blog
:
- 如果我将
与motor\u客户端
一起使用,结果大约是“1500个请求/秒”wait
- 如果我将其更改为
(同步模式),结果约为“1900个请求/秒”pymongo_client
gunicorn-w4-kuvicorn.workers.UvicornWorker我的博客:app
运行starlette应用程序,只需切换这两行即可执行wrk
基准测试
我做了搜索,但找不到谈论这个的帖子,所以我想知道我是否错过了什么?非常感谢您的帮助。可能是因为电机实际上不是异步驱动器。它只是在ThreadPoolExecutor中启动同步pymongo,因此性能下降。不幸的是,目前python上没有mongo的异步驱动程序:(您连续运行查询,但当motor客户端返回到事件循环时,检查挂起的任务/未来等的开销。您应该查看
asyncio.gather
,以允许一次运行多个查询。@dirn感谢您的反馈,但我不确定我是否了解您的意思。在这个请求中ndler,我只有一个查询,类似于cursor=motor\u client.blog.find({})
然后将其转换为列表,如wait[item async for item in cursor]
。我在这个句柄中没有多个查询哦,你说得对。我错误地将其理解为对查询的迭代。wait[item asymc for item in…]
work?看起来像是个错误。@user4815162342对,这是伪代码,很抱歉造成混淆,在我的实际代码中,我将[item async for item in cursor]
在一个异步函数中,所以我需要等待它。如果只是返回列表,就不需要等待它。无论如何,对于伪代码的混淆,我感到很抱歉。但是motor明显比原生pymongo慢的基准测试部分真的让我很困惑