zoukankan      html  css  js  c++  java
  • twisted adbapi 连接超时中断重连,Lost connection ,cp_reconnect=True 参数不好用 ,2006, 2013 MySQLdb.OperationalError

    转载  

    https://stackoverflow.com/questions/12677246/twisted-adbapi-cp-reconnect-not-working/35178822


    重写adbapi.ConnectionPool
    
    

    class ReconnectingMySQLConnectionPool(adbapi.ConnectionPool):
    """
    This connection pool will reconnect if the server goes away. This idea was taken from:
    https://stackoverflow.com/questions/12677246/twisted-adbapi-cp-reconnect-not-working/35178822
    """

    def _runInteraction(self, interaction, *args, **kw):
    try:
    return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
    except MySQLdb.OperationalError as e:
    if e.args[0] not in (2006, 2013):
    raise
    logger.error("Lost connection to MySQL, retrying operation. If no errors follow, retry was successful.")
    conn = self.connections.get(self.threadID())
    self.disconnect(conn)
    return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)


    -------------------

    加强版


    class ReconnectingMySQLConnectionPool(adbapi.ConnectionPool):
    """
    This connection pool will reconnect if the server goes away. This idea was taken from:
    https://stackoverflow.com/questions/12677246/twisted-adbapi-cp-reconnect-not-working/35178822
    """

    def _runInteraction(self, interaction, *args, **kw):

    #

    i = 0
    while i <= 10:
    try:
    return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
    except MySQLdb.OperationalError as e:
    if e.args[0] not in (2006, 2013):
    raise
    logger.error(
    "Lost connection to MySQL, retrying operation. If no errors follow, retry was successful.")
    # time.sleep(0.1)
    conn = self.connections.get(self.threadID())
    self.disconnect(conn)
    i += 1
    logger.info("Lost connection 重试__%s" % str(i))

    raise MySQLdb.OperationalError("Lost connection to MySQL")



    ----------------
    使用处



    class MysqlTwistedPipline(object):
    def __init__(self, dbpool):
    self.dbpool = dbpool

    @classmethod
    def from_settings(cls, settings):
    # 参数名称 要 一致
    dbparms = dict(
    host=settings['MYSQL_HOST'],
    user=settings['MYSQL_USER'],
    passwd=settings['MYSQL_PASSWORD'],
    db=settings['MYSQL_DBNAME'],
    charset='utf8',
    cursorclass=MySQLdb.cursors.DictCursor,
    use_unicode=True,
    cp_reconnect=True
    )

    # dbpool = adbapi.ConnectionPool("MySQLdb", **dbparms)
    dbpool = ReconnectingMySQLConnectionPool("MySQLdb", **dbparms)

    return cls(dbpool)
     
  • 相关阅读:
    深入浅出java IO模型
    MySQL 最基本的SQL语法/语句
    mysql sql常用语句大全
    Mysql数据库常用操作语句大全
    python3.6.1 安装PyQt5,以及配置QTDesigner,PyUIC
    Python之文件操作:os模块
    Python之OS模块函数
    Python OS模块
    Shell编程基础
    mysqldump恢复
  • 原文地址:https://www.cnblogs.com/angdh/p/14071486.html
Copyright © 2011-2022 走看看