我有一个 Web 应用程序,每分钟有数千个请求。以下是我用于 mongoDB 连接的 python 代码:
工具.py:
globalconnection = None
def getCollection(name,safe=False,readpref=ReadPreference.PRIMARY):
global globalconnection
while globalconnection is None:
try:
if not globalconnection is None:
globalconnection.close()
globalconnection = Connection('mongodb://host:port',replicaSet='mysetname',safe=False,read_preference=ReadPreference.PRIMARY,network_timeout=30,max_pool_size=1024)
except Exception as e:
globalconnection = None
request_context.connection = globalconnection
return request_context.connection["mydb"]["mycoll"]
网页.py
@app.route("/test")
def test():
request_collection = getCollection("user")
results = request_collection.find()
for result in results:
#do something...
request_collection.save(result)
request_collection.end_request()
一个http请求通过这个函数获取连接,
并且http请求在请求结束之前调用end_request。
但是我发现在增加请求的同时,mongoDB中有很多AutoReconnect错误和超过20000个连接。
你有什么建议吗?