扭曲的adbapi cp_重新连接不工作

2024-10-05 12:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个与MySQL数据库对话的clone web服务。当有一段时间没有活动(我猜超过8个小时),在重新启动web服务之前,我会出现以下错误:

_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

我见过this post regarding cp_reconnect,我在创建连接池时实现了这一点:

pool = adbapi.ConnectionPool("MySQLdb", host=self.host, user=self.user,
    passwd=self.password, db=self.database, cursorclass=MySQLdb.cursors.DictCursor,
    cp_reconnect=True)

我本以为这样可以解决它,而且似乎已经解决了一段时间,但现在我看到“MySQL服务器已经离开”错误,因为服务器上有一段时间没有活动。在

我已经读过this MySQL documentation regarding wait_timeout,我想我可以用这种方式修复它,但是为什么cp峎u重新连接特性对我不起作用呢?我对adbapi文档的解释是,如果您指定cp_reconnect参数,则adbadpi将处理MySQL发送的错误并重新尝试查询。所以基本上你不必直接在代码中处理错误。我误解了吗?在


Tags: self服务器web数据库host错误mysql对话
3条回答

在对twisted邮件列表进行了一些讨论并查看了twisted bug tracker之后,发现这是一个尚未修复的已知bug。在

这是指向mailing list discussion的链接。在

这是指向twisted bug tracker issue的链接。在

可能的解决方案:

  1. 增加服务器上的等待超时值。在
  2. 重写ConnectionPool类referenced above中的方法。在
  3. 在每个连接中设置一个周期性的“ping”来保持连接。在
  4. 自己修复adbapi中的错误。在

其中,我可能会选择1。在

链接http://www.gelens.org/2009/09/13/twisted-connectionpool-revisited/不再工作,甚至Web存档版本也不起作用。以下是Twistar 1.3的一段摘录,其中提到了相同的解决方案:

https://pypi.python.org/pypi/twistar

class ReconnectingMySQLConnectionPool(adbapi.ConnectionPool):
    """
    This connection pool will reconnect if the server goes away.  This idea was taken from:
    http://www.gelens.org/2009/09/13/twisted-connectionpool-revisited/
    """
    def _runInteraction(self, interaction, *args, **kw):
        try:
            return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
        except MySQLdb.OperationalError, e:
            if e[0] not in (2006, 2013):
                raise
            log.err("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)

几年前我就在寻找解决办法。我在网上找到的解决方案是子类化ConnectionPool并重写{},在这里可以强制重新连接特定的错误代码。 一个快速的谷歌搜索将我带到这个网站:http://www.gelens.org/2009/09/13/twisted-connectionpool-revisited/,其中包含一个代码。 我再也不用考虑MySQL连接的死机了。在

相关问题 更多 >

    热门问题