首页 > 技术文章 > pymongo AutoReconnect,自动重连问题

jackduan 2019-11-27 10:46 原文

https://blog.csdn.net/qq_29719097/article/details/80650742

当连接异常时,用try   expect, 使用retry获取异常后重复操作


import pymongo
from pymongo.errors import AutoReconnect
from retrying import retry
collection = pymongo.MongoClient(host='192.168.1.222', port=27017,serverSelectionTimeoutMS=5000, socketTimeoutMS=5000).ali.ocr
def retry_if_auto_reconnect_error(exception):
    """Return True if we should retry (in this case when it's an AutoReconnect), False otherwise"""
    return isinstance(exception, AutoReconnect)
#连接失效异常,自动重连
@retry(retry_on_exception=retry_if_auto_reconnect_error, stop_max_attempt_number=2, wait_fixed=2000)
def insertmongo(collection,mydict):
    collection.insert_one(mydict)

 

推荐阅读