gpt4 book ai didi

python - ZODB 提交卡住并使我的整个应用程序卡住

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:04 25 4
gpt4 key购买 nike

今天我在使用 ZODB 的 Python 应用程序上发现了一个错误。试图找出我的应用程序卡住的原因,我认为 ZODB 是原因。

将日志记录设置为调试,似乎在提交时,ZODB 会发现 2 个连接,然后开始卡住。

INFO:ZEO.ClientStorage:('127.0.0.1', 8092) Connected to storage: ('localhost', 8092)
DEBUG:txn.140661100980032:new transaction
DEBUG:txn.140661100980032:commit
DEBUG:ZODB.Connection:Committing savepoints of size 1858621925
DEBUG:discord.gateway:Keeping websocket alive with sequence 59.
DEBUG:txn.140661100980032:commit <Connection at 7fee2d080fd0>
DEBUG:txn.140661100980032:commit <Connection at 7fee359e5cc0>

由于我是 ZODB 初学者,对于如何解决/如何深入挖掘有什么想法吗?

似乎与并发提交有关。

我相信打开一个新连接会启动一个专用的事务管理器,但事实并非如此。在不指定事务管理器的情况下启动新连接时,将使用本地连接(与线程上的其他连接共享)。

我的代码:

async def get_connection():
return ZEO.connection(8092)

async def _message_db_init_aux(self, channel, after=None, before=None):
connexion = await get_connection()
root = connexion.root()

messages = await some_function_which_return_a_list()

async for message in messages:
# If author.id doesn't exist on the data, let's initiate it as a Tree
if message.author.id not in root.data: # root.data is a BTrees.OOBTree.BTree()
root.data[message.author.id] = BTrees.OOBTree.BTree()

# Message is a defined classed inherited from persistant.Persistant
root.data[message.author.id][message.id] = Message(message.id, message.author.id, message.created_at)

transaction.commit()
connexion.close()

最佳答案

不要跨连接重复使用事务管理器。每个连接都有自己的事务管理器,使用它

您的代码当前创建连接,然后提交。不要创建连接,而是要求数据库为您创建一个事务管理器,然后由该管理器管理自己的连接。事务管理器可以用作上下文管理器,这意味着当上下文结束时会自动提交对数据库的更改。

此外,通过对每个事务使用 ZEO.connection() ,您将强制 ZEO 创建一个完整的新客户端对象,并具有新的缓存和连接池。通过使用 ZEO.DB() 代替并缓存结果,可以创建一个客户端,可以从中池化和重用连接,并使用本地缓存来加速事务处理。

我将代码更改为:

def get_db():
"""Access the ZEO database client.

The database client is cached to take advantage of caching and connection pooling

"""
db = getattr(get_db, 'db', None)
if db is None:
get_db.db = db = ZEO.DB(8092)
return db

async def _message_db_init_aux(self, channel, after=None, before=None):
with self.get_db().transaction() as conn:
root = conn.root()

messages = await some_function_which_return_a_list()

async for message in messages:
# If author.id doesn't exist on the data, let's initiate it as a Tree
if message.author.id not in root.data: # root.data is a BTrees.OOBTree.BTree()
root.data[message.author.id] = BTrees.OOBTree.BTree()

# Message is a defined classed inherited from persistant.Persistant
root.data[message.author.id][message.id] = Message(
message.id, message.author.id, message.created_at
)

数据库对象上的 .transaction() 方法在进入上下文时会在后台创建一个新连接(with 导致 __enter__ 被调用),当 with block 结束时,事务被提交,连接再次被释放到池中。

请注意,我使用了同步 def get_db() 方法; ZEO 客户端代码上的调用签名是完全同步的。从异步代码中调用它们是安全的,因为在底层,实现自始至终都使用 asyncio,在同一循环上使用回调和任务,并且实际 I/O 被推迟到单独的任务。

关于python - ZODB 提交卡住并使我的整个应用程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239533/

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