[英]keep a continuous mongo connection active using pymongo
I have a consumer reading from kafka which has a continuous stream of events, every so often I have to write to a mongo collection for which I have to have a continuous mongo connection open. 我有一个来自kafka的消费者阅读,它有连续的事件流,我经常要写一个mongo集合,我必须打开一个连续的mongo连接。 My solution to this which is fairly hacky I feel is to re-initialize the connection every 5 minutes or so to avoid Network timeout.
我的解决方案是相当hacky我觉得是每5分钟左右重新初始化一次连接以避免网络超时。 This is to avoid periods in which there are no events from kafka and the connection is idle.
这是为了避免kafka没有事件且连接空闲的时段。
Can anyone suggest a better way to do this? 任何人都可以提出更好的方法吗? Since I'm pretty sure this is the wrong way to go about establishing a continuous connection to mongo.
因为我很确定这是建立与mongo的连续连接的错误方法。
I'm using the pymongo client. 我正在使用pymongo客户端。
I have a MongoAdapter class which has helper methods: 我有一个MongoAdapter类,它有辅助方法:
from pymongo import MongoClient
import pymongo
import time
class MongoAdapter:
def __init__(self,databaseName,userid,password,host):
self.databaseName=databaseName
self.userid=userid
self.password=password
self.host=host
self.connection=MongoClient(host=self.host,maxPoolSize=100,socketTimeoutMS=1000,connectTimeoutMS=1000)
self.getDatabase()
def getDatabase(self):
try:
if(self.connection[self.databaseName].authenticate(self.userid,self.password)):
print "authenticated true"
self.database=self.connection[self.databaseName]
except pymongo.errors.OperationFailure:
print "Error: Please check Database Name, UserId,Password"
and I use the class in the following way to re-connect: 我按以下方式使用该类重新连接:
adapter_reinit_threshold=300 #every 300 seconds, instantiate new mongo conn.
adapter_config_time=time.time()
while True
if (time.time()-adapter_config_time) > adapter_reinit_threshold:
adapter=MongoAdapter(config.db_name,config.db_user,config.db_password,config.db_host) #re-connect
adapter_config_time=time.time() #update adapter_config_time
The reason I went ahead and did it this way was because I thought the old unused objects (with open connections, would be garbage collected and connections closed). 我继续这样做的原因是因为我认为旧的未使用的对象(具有开放连接,将被垃圾收集并且连接关闭)。 Although this method works fine, I want to know if there's a cleaner way to do it and what the pitfalls of this approach might be.
虽然这种方法工作正常,但我想知道是否有更简洁的方法来实现它,以及这种方法的缺陷是什么。
From the documentation of pymongo.mongo_client.MongoClient 来自pymongo.mongo_client.MongoClient的文档
If an operation fails because of a network error, ConnectionFailure is raised and the client reconnects in the background.
如果由于网络错误导致操作失败,则会引发ConnectionFailure,并且客户端将在后台重新连接。 Application code should handle this exception (recognizing that the operation failed) and then continue to execute.
应用程序代码应处理此异常(识别操作失败),然后继续执行。
I don't think you need to implement your own re-connection method. 我认为您不需要实现自己的重新连接方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.