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)
     
  • 相关阅读:
    【jQuery】用jQuery给文本框添加只读属性【readOnly】
    解决embed标签显示在div上层【转藏】
    width:100% 和 max-width:100%; 有区别吗【转藏】
    一位资深程序员的独白
    jQuery 取值、赋值的基本方法【转藏】
    js判断手机端操作系统(Andorid/IOS)
    PhpStrom 和 wamp 配置 xdebug
    php 中 ?? 和 empty 的 区别
    phpSpreadSheet 中 使用的 一些坑
    html td 限制 高度 和 宽度
  • 原文地址:https://www.cnblogs.com/angdh/p/14071486.html
Copyright © 2011-2022 走看看