如何使用 python 增加 Mongodb 的连接池大小

How to increase connection pool size for Mongodb using python

我正在使用 Mongodb 作为项目的数据库,我每秒向 mongodb 发送 1000 个请求。我观察到,与排在队列最后的请求相比,排在队列前面的请求工作得更快。恐怕如果调用 mongodb 增加它会消耗更多时间。我认为我可以使用池 connection.If 进行管理 是的,让我知道我们如何使用 python.If 增加池大小 没有建议我任何其他选择

以下是查找具有字段 snippetid 的文档的一些结果,我有索引

一些提前发送的请求

db.collection.find({'snippetid': '55a0466a414353801e4ff16a'})

Time Taken 0.00563097000122

db.collection.find({'snippetid': '559417cd5217d572fa120a21'})

Time Taken 0.00330901145935

有些请求在队列中排在最后

db.collection.find({'snippetid': '55a4b1d45217d5e7609e19b2'})

Time Taken 1.95499396324

db.collection.find({'snippetid': '55a059d5be98fa09168b63f9'})

Time Taken 1.96221590042

来自 MongoClient 的 pymongo 文档:

maxPoolSize (optional): The maximum number of connections that the pool will open simultaneously. If this is set, operations will block if there are maxPoolSize outstanding connections from the pool. Defaults to 100. Cannot be 0.

并给出签名:

 pymongo.mongo_client.MongoClient(
     host='localhost', port=27017, document_class=dict,
     tz_aware=False, connect=True, **kwargs)

因此在该调用中添加 maxPoolSize 和您想要的值将设置连接池的大小。

请注意 "nothing is free",这是以客户端和服务器维护大量连接的明显成本为代价的。对于高请求负载,您可能会考虑其他处理方法,或者至少平衡负载。

嘿,您可以使用 pymongo 增加 python 中的池大小。 语法

from pymongo import MongoClient
client = MongoClient('host', port, maxPoolSize=200)

有关详细信息,请查看 link