gpt4 book ai didi

python mysql.connector 连接断开时写入失败停滞 30 秒

转载 作者:行者123 更新时间:2023-11-29 19:18:46 30 4
gpt4 key购买 nike

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

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

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

现在我的问题是“请求失败”,失败需要很长时间。只有这样我才能重新连接并重试我的请求。 (我已经在代码片段中以注释的形式指出了这一点)。

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

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

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>

最佳答案

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

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

或者,您偶尔可以执行无操作查询,例如 select now(); 以保持连接打开。您仍然希望经常回收连接。

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

关于python mysql.connector 连接断开时写入失败停滞 30 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42550807/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com