[英]Prevent MongoDB race condition in update query during multiple requests
I have a simple web application in Flask and I use Mongoengine as ORM.我在 Flask 中有一个简单的 web 应用程序,我使用 Mongoengine 作为 ORM。 The API takes in a request, adds the request to a worker queue, decreases the user's license count and save it back.
API 接收请求,将请求添加到工作队列,减少用户的许可证计数并将其保存回来。 Example code given below:
下面给出的示例代码:
def process_request(body):
user = User.objects.get(username=username_from_session)
add_request_to_worker_queue(body['data'])
user.total_license_count = user.total_license_count - 1
user.save()
This works as expected.这按预期工作。 But I noticed when multiple requests are sent from the same user at the same time, the license_count is not decreased as expected.
但是我注意到,当同一用户同时发送多个请求时,license_count 并没有按预期减少。 I suppose this is because the other requests do not see the update of the first request as it is still processing.
我想这是因为其他请求没有看到第一个请求的更新,因为它仍在处理中。
I tried adding a random delay to the requests but it did not help.我尝试在请求中添加随机延迟,但没有帮助。 I don't know if there is some form of lock mechanism in MongoDB to wait till the other process finishes processing.
我不知道 MongoDB 中是否有某种形式的锁定机制来等待其他进程完成处理。 How do I fix this to prevent this from happening.
我该如何解决这个问题以防止这种情况发生。
My stack is Python, Flask, Mongoengine, MongoDB我的堆栈是 Python,Flask,Mongoengine,MongoDB
Use conditional updates, set condition as license_count > 0, use $inc operator to perform the decrement and read the number of updates done to see if the count started out positive.使用条件更新,将条件设置为 license_count > 0,使用 $inc 运算符执行递减并读取完成的更新次数以查看计数是否开始为正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.