简体   繁体   English

如何避免数据库锁定

[英]How to avoid db lock

I am working on the backend of a game. 我正在开发游戏的后端。 Players first purchase their tickets, which are stored into the database, then they play and can win certain prizes. 玩家首先购买他们的门票,并将其存储在数据库中,然后他们进行游戏并可以赢得某些奖品。 Each player can buy a max of 60 tickets. 每个玩家最多可以购买60张门票。

A new requirement appeared, setting an upper bound for the total number of tickets per game - 10 000 tickets. 出现了一个新要求,为每场比赛的总票数设置了上限-10,000张。 The implementation would involve adding to the purchase endpoint a test checking that the total number of purchased tickets at that time + number of tickets required on current purchase is less or equal to the max number of tickets for that game, in order for a purchase to be accepted. 该实现将涉及向购买端点添加一个测试,以检查当时购买的门票总数+当前购买所需的门票数量小于或等于该游戏的最大门票数量,以便进行购买。被接受。

The problem is that, calculating the current number of purchased tickets by using count on the tickets table, the returned value may be out-of-date because in the meantime other players could have purchased tickets. 问题是,通过使用票证表上的计数来计算当前购买的票证数量,返回的值可能已过期,因为与此同时其他玩家可能已经购买了票证。

A possible solution is to lock the tickets table during the purchase, but this can have a negative impact on performance and user experience. 一种可能的解决方案是在购买期间锁定票证表,但这可能会对性能和用户体验产生负面影响。 Please let me know if you have a different idea. 如果您有其他想法,请告诉我。

If yours is a hard constraint then you must avoid multiple purchases being conducted concurrently. 如果您的要求很严格,则必须避免同时进行多次购买。 Probably an appropriate table lock in the DB is the best way to accomplish such serialization. 在数据库中适当的表锁可能是完成此类序列化的最佳方法。 There could be other alternatives (ie performing the serialization somewhere in the front end), but they are likely to be messier to implement, more prone to bugs, and worse-performing. 可能还有其他选择(即在前端某处执行序列化),但是它们可能实现起来更麻烦,更容易出现错误以及性能更差。

In fact, it may be difficult to make your game exhibit consistent behavior at all without appropriate locking in the DB. 实际上,如果没有适当锁定数据库,可能很难使您的游戏表现出始终一致的行为。 On the other hand, you probably don't need explicit locking. 另一方面,您可能不需要显式锁定。 If you configure your database with an appropriate transaction isolation level then it should do all necessary locking for you. 如果为数据库配置了适当的事务隔离级别,则它应该为您执行所有必要的锁定。

Since there's no clear win to be had here, I recommend shelving the performance question until you can actually test your performance. 由于这里没有明显的胜利,因此我建议搁置性能问题,直到您可以实际测试性能为止。 If it turns out not to be good enough then you can determine from actual measurement what parts of the system can most benefit from tuning. 如果结果还不够好,则可以从实际测量中确定系统的哪些部分最受益于调整。

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

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