偶尔的“ConnectionError:无法连接到数据库”mongo
问题描述:
我们正在测试一个基于django的项目,它使用MongoEngine作为持久层。 MongoEngine基于pymongo,我们使用的是1.6版,我们正在运行一个mongo的单一实例设置。偶尔的“ConnectionError:无法连接到数据库”mongo
我们注意到的是,偶尔约5分钟,连接不能建立到mongo实例。有没有人遇到过这种行为?关于如何提高可靠性的任何提示?
答
我们遇到了AutoReconnect
这个问题,这听起来与您所描述的相似。我结束了我的<project>/__init__.py
文件的Monkeypatching pymongo:
from pymongo.cursor import Cursor
from pymongo.errors import AutoReconnect
from time import sleep
import sys
AUTO_RECONNECT_ATTEMPTS = 10
AUTO_RECONNECT_DELAY = 0.1
def auto_reconnect(func):
"""
Function wrapper to automatically reconnect if AutoReconnect is raised.
If still failing after AUTO_RECONNECT_ATTEMPTS, raise the exception after
all. Technically this should be handled everytime a mongo query is
executed so you can gracefully handle the failure appropriately, but this
intermediary should handle 99% of cases and avoid having to put
reconnection code all over the place.
"""
def retry_function(*args, **kwargs):
attempts = 0
while True:
try:
return func(*args, **kwargs)
except AutoReconnect, e:
attempts += 1
if attempts > AUTO_RECONNECT_ATTEMPTS:
raise
sys.stderr.write(
'%s raised [%s] -- AutoReconnecting (#%d)...\n' % (
func.__name__, e, attempts))
sleep(AUTO_RECONNECT_DELAY)
return retry_function
# monkeypatch: wrap Cursor.__send_message (name-mangled)
Cursor._Cursor__send_message = auto_reconnect(Cursor._Cursor__send_message)
# (may need to wrap some other methods also, we'll see...)
这解决了这个问题对我们来说,但你可能会说明一些不同的东西?
答
这是另一种使用子类而不是猴子修补的解决方案,它处理建立初始连接时或访问数据库时可能引发的错误。我只是继承了Connection/ReplicasetConnection,并在实例化和任何方法调用期间处理了引发的AutoReconnect错误。您可以在构造函数中指定重试次数和重试之间的休眠时间。
你可以看到这里的要点是:https://gist.github.com/2777345
好像如果我们发现有不同 – 2011-03-15 12:39:19
任何最新发展有助于这个可能解决我们的问题..我要让你知道吗? – Climax 2014-04-29 13:26:25