简体   繁体   English

用Java非阻塞MySQL更新?

[英]Non-blocking MySQL updates with java?

For a multiplayer game I'm working on I'd like to record events to the mysql database without blocking the game update thread so that if the database is busy or a table is locked the game doesn't stop running while it waits for a write. 对于我正在开发的多人游戏,我想在不阻止游戏更新线程的情况下将事件记录到mysql数据库中,以便在数据库繁忙或表被锁定的情况下,游戏在等待更新时不会停止运行写。

What's the best way to accomplish this? 做到这一点的最佳方法是什么?

I'm using c3p0 to manage the database connection pool. 我正在使用c3p0来管理数据库连接池。 My best idea so far is to add query update strings to a synchronized list with an independent thread checking the list every 100ms and executing the queries it finds there. 到目前为止,我最好的主意是将查询更新字符串添加到同步列表中,并使用一个独立的线程每100毫秒检查一次列表并执行在该列表中找到的查询。

Place updates on a BlockingQueue . 将更新放在BlockingQueue Have a separate thread wait on the queue with take() , followed by drainTo() to consume all pending updates and push them to the server in one go. 让一个单独的线程使用take()在队列上等待,然后使用drainTo()使用所有待处理的更新并将它们一次性推送到服务器。 Use a single multi-row INSERT for maximum efficiency. 使用单个多行INSERT可获得最高效率。

This approach ensures that updates hit the server without any gratuitous delay due to polling frequency, while making chunkier, and thus more efficient, requests as volume climbs. 这种方法可确保更新在轮询服务器时不会因轮询频率而造成任何不必要的延迟,同时随着卷的增加而发出更块状的请求,从而提高了请求的效率。

My best idea so far is to add query update strings to a synchronized list with an independent thread checking the list every 100ms and executing the queries it finds there. 到目前为止,我最好的主意是将查询更新字符串添加到同步列表中,并使用一个独立的线程每100毫秒检查一次列表并执行在该列表中找到的查询。

This sounds good to me if you don't want to block your main thread, except that don't use synchronized list and 100ms polling, but use some BlockingQueue implementation instead. 如果您不想阻塞主线程,那对我来说听起来不错,除了不使用同步列表和100ms轮询,而是使用某些BlockingQueue实现。 LinkedBlockingQueue should do the job, if you make it unbounded it will never block your main thread. LinkedBlockingQueue应该可以完成这项工作,如果使它不受限制,它将永远不会阻塞主线程。

I think an "INSERT DELAYED" might be what you're looking for, as the INSERT returns immediately, and MySQL will handle all the threading issues for you. 我认为您可能正在寻找“ INSERT DELAYED”,因为INSERT立即返回,而MySQL将为您处理所有线程问题。 There is no equivalent UPDATE statement, however, so you'd need to rewrite your code so you're only using INSERTs or REPLACEs. 但是,没有等效的UPDATE语句,因此您需要重写代码,以便仅使用INSERT或REPLACE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM