2011-03-13 60 views
0

我們正在測試一個基於django的項目,它使用MongoEngine作爲持久層。 MongoEngine基於pymongo,我們使用的是1.6版,我們正在運行一個mongo的單一實例設置。偶爾的「ConnectionError:無法連接到數據庫」mongo

我們注意到的是,偶爾約5分鐘,連接不能建立到mongo實例。有沒有人遇到過這種行爲?關於如何提高可靠性的任何提示?

回答

2

我們遇到了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...) 

這解決了這個問題對我們來說,但你可能會說明一些不同的東西?

+0

好像如果我們發現有不同 – 2011-03-15 12:39:19

+0

任何最新發展有助於這個可能解決我們的問題..我要讓你知道嗎? – Climax 2014-04-29 13:26:25

1

這是另一種使用子類而不是猴子修補的解決方案,它處理建立初始連接時或訪問數據庫時可能引發的錯誤。我只是繼承了Connection/ReplicasetConnection,並在實例化和任何方法調用期間處理了引發的AutoReconnect錯誤。您可以在構造函數中指定重試次數和重試之間的休眠時間。

你可以看到這裏的要點是:https://gist.github.com/2777345