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)
 
原文地址:https://www.cnblogs.com/angdh/p/14071486.html