【问题标题】:python mysql.connector write failure on connection disconnection stalls for 30 secondspython mysql.connector在连接断开时写入失败停顿30秒
【发布时间】:2017-07-21 21:45:24
【问题描述】:

我使用 python 模块 mysql.connector 连接到 AWS RDS 实例。

现在,我们知道,如果我们有一段时间没有向 SQL Server 发送请求,连接就会断开。

为了处理这个问题,我会重新连接到 SQL,以防读/写请求失败

现在我的问题是 “请求失败”,失败非常重要。只有这样我才能重新连接并重试我的请求。 (我已将其作为代码 sn-p 中的注释指出)。

对于像我这样的实时应用程序,这是一个问题。我怎么能解决这个问题?是否可以查明断开连接是否已经发生,以便我可以尝试新的连接而无需等待读/写请求?

这是我现在在代码中处理它的方式:

def fetchFromDB(self, vid_id):
    fetch_query = "SELECT * FROM <db>"
    success = False
    attempts = 0
    output = []
    while not success and attempts < self.MAX_CONN_ATTEMPTS:
        try:
            if self.cnx == None:
                self._connectDB_()

            if self.cnx:
                cursor = self.cnx.cursor() # MY PROBLEM: This step takes too long to fail in case the connection has expired.
                cursor.execute(fetch_query)

                output = []
                for entry in cursor:
                    output.append(entry)
                cursor.close()
                success = True
            attempts = attempts + 1
        except Exception as ex:
            logging.warning("Error")
            if self.cnx != None:
                try:
                    self.cnx.close()
                except Exception as ex:
                    pass
                finally:
                    self.cnx = None
    return output

在我的应用程序中,从 mysql 读取时,我不能容忍超过 1 秒的延迟。
在配置 mysql 时,我只做以下设置:

SQL.user = '<username>'
SQL.password = '<password>'
SQL.host = '<AWS RDS HOST>'
SQL.port = 3306
SQL.raise_on_warnings = True
SQL.use_pure = True 
SQL.database = <database-name>

【问题讨论】:

    标签: python mysql mysql-connector mysql-connector-python mysqlconnection


    【解决方案1】:

    如果函数调用时间过长,则有一些设计,例如生成 ALARM 信号或类似信号。这些对于数据库连接可能很棘手,或者根本不起作用。那里有other SO questions

    一种方法是在创建连接时将connection_timeout 设置为已知值,确保它比server side timeout 短。然后,如果您自己跟踪连接的年龄,您可以在它变得太旧之前抢先重新连接并清理以前的连接。

    或者,您可以偶尔执行诸如select now(); 之类的无操作查询以保持连接打开。您仍然希望每隔一段时间回收一次连接。

    但如果查询之间有足够长的时间段(它们可能会过期),为什么不为每个查询打开一个新连接?

    【讨论】:

    • 查询之间的时间不固定。有时我们会在短时间内收到很多查询。有时,间隔可能长达 5 分钟。我正在考虑您提到的无操作查询方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2017-01-06
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多