本文介绍了使用mongodb在nodejs中使用锁定/事务读取和插入文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在预订系统中,只有 5 个不同的用户可以创建预订.如果 100 个用户同时调用预订 api,那么如何通过锁定处理并发.我在 mongodb 中使用 nodejs.我浏览了 mongo 并发文章 here 和 mongodb 中的事务,但找不到任何示例带锁定的编码解决方案.

In reservation system, only 5 different user can create bookings. If 100 user call booking api at same time than how to handle concurrency with locking. I am using nodejs with mongodb. I went through mongo concurrency article here and transactions in mongodb, but cannot find any sample coding solution with locking.

我已经通过乐观并发控制实现了解决方案(当资源争用较少时 - 这可以使用 versionNumber 或 timeStamp 字段轻松实现).

I have achieved solution with Optimistic concurrency control (when there is low contention for the resource - This can be easily implemented using versionNumber or timeStamp field).

预先感谢您向我建议使用锁定的解决方案.

Thank you in advance for suggesting me solution with locking.

现在算法是,

第 1 步:从 userSettings 集合中获取 userAllowedNumber.

Step 1: Get userAllowedNumber from userSettings collection.

查询:db.getCollection('userSettings').find({})

Query: db.getCollection('userSettings').find({})

响应数据:

{
   "userAllowedNumber": 5
}

第 2 步,从预订集合中获取当前的 bookedCount.

Step 2, Get current bookedCount from bookings collection.

查询:db.getCollection('bookings').count({ })

Query: db.getCollection('bookings').count({ })

响应数据:2

第 3 步,如果 bookedCount

Step 3, if bookedCount <= userAllowedNumber then insert in bookings.

查询:db.getCollection('bookings').create({ user_id: "usr_1" })

Query: db.getCollection('bookings').create({ user_id: "usr_1" })

推荐答案

我在 mongodb 社区中深入讨论了事务锁定.在结论中,我学习并发现了交易的局限性.我们没有可以用来处理此任务的并发请求的锁.

I had deep discussion about locking with transaction in mongodb community. In the conclusion, I learn and found the limitation of transaction. There is no lock we can use to handle concurrent request for this task.

您可以在此链接中查看完整的 Mongodb 社区对话https://www.mongodb.com/community/forums/t/implementing-locking-in-transaction-for-read-and-write/127845

You can see the full Mongodb community conversation at this linkhttps://www.mongodb.com/community/forums/t/implementing-locking-in-transaction-for-read-and-write/127845

带有 Jmeter 测试的 Github 演示代码显示了限制并且无法处理此任务的并发请求.https://github.com/naisargparmar/concurrencyMongo

Github demo code with Jmeter testing shows the limitation and not able to handle concurrent request for this task.https://github.com/naisargparmar/concurrencyMongo

仍然欢迎和欣赏新的建议

New suggestion are still welcome and appreciate

这篇关于使用mongodb在nodejs中使用锁定/事务读取和插入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:10