現在、MongoEngine を永続化レイヤーとして使用する django ベースのプロジェクトをテストしています。MongoEngine は pymongo に基づいており、バージョン 1.6 を使用しており、mongo の単一インスタンス セットアップを実行しています。
私たちが気づいたことは、時折、約 5 分間、mongo インスタンスへの接続を確立できないことです。誰かがそのような行動に出くわしましたか? 信頼性を向上させるためのヒントはありますか?
AutoReconnect
あなたが説明しているものに似た音の問題がありました。私は自分のファイルにpymongoをモンキーパッチしました<project>/__init__.py
:
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