如何解决SQLAlchemy 正确处理死锁
我正在使用 sqlAlchemies 异步引擎进行以下初始化,并希望从死锁中恢复。由于我在文档中找不到任何相关信息,我决定使用 timeout 参数。
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine(
database_url,connect_args={'timeout': timeout},pool_size=16,max_overflow=10
)
我现在面临的问题是我找不到从 TimeoutErrors 中恢复的正确方法。
尝试第 1 次
for i in range(max_retries):
try:
async with self.engine.connect() as conn:
async with conn.begin() as transaction:
output = await conn.execute(query)
except asyncio.exceptions.TimeoutError as te:
logger.info(f"Connection timeout! Trying again. Attempt: {i + 1}/{max_retries}")
else:
return output
导致以下错误:
asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation
尝试第 2 次strong>
for i in range(max_retries):
try:
async with self.engine.connect() as conn:
transaction = await conn.begin()
try:
output = await conn.execute(query)
await transaction.commit()
except:
await transaction.rollback()
await transaction.close()
continue
else:
await transaction.close()
return output
except asyncio.exceptions.TimeoutError as te:
logger.info(f"Connection timeout! Trying again. Attempt: {i + 1}/{max_retries}")
else:
return output
导致以下错误:
asyncio.exceptions.InvalidStateError: invalid state
所以我的问题是,我该怎么办?
编辑
经过进一步测试,我意识到超时参数不起作用。当死锁发生时,sqlAlchemy 停止响应并且 asyncio 用以下消息填充日志:
INFO:asyncio:poll 55776.892 ms took 55832.809 ms: timeout
INFO:asyncio:poll 50130.676 ms took 50181.180 ms: timeout
INFO:asyncio:poll 60008.691 ms took 60031.415 ms: timeout
INFO:asyncio:poll 29676.484 ms took 29706.735 ms: timeout
INFO:asyncio:poll 30080.565 ms took 30111.141 ms: timeout
INFO:asyncio:poll 60180.535 ms took 60234.353 ms: timeout
有趣的是,应用程序的其余部分不受它的影响并继续按预期工作。
更多信息
使用 MysqL 而不是 Postgresql 时也会出现此问题。 不执行选择或更新查询。对大约 300 个不同的表执行大约 1000 次插入的突发足以以一定的概率导致此问题。在我们的应用程序中,引擎在使用大约 10 分钟后锁定。我们发现缓解此问题的唯一方法是每 5 分钟终止并重新启动 python 脚本。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。