在Node.js中防止并发 [英] Prevent Concurrency In Nodejs

查看:176
本文介绍了在Node.js中防止并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Nodejs(Express)中建立了一个电子商务后端,可以说有一种产品,只剩下
的数量,两个用户试图同时购买该产品,而这两个产品都使该产品减负Mysql Db数量部分中的值

I have built a Ecommerce Backend in Nodejs(Express), Lets say there a product and only 1 quantity is left and two users are trying to buy that product at the same time both are getting that product leaving minus value in the quantity section of my Mysql Db

如何摆脱这种情况,建议会有所帮助

How to get rid of this , Suggestions will be helpful

谢谢

推荐答案

数据库事务隔离级别

Database Transaction Isolation Levels

这可以通过利用以下方法在数据库中进行保证:您的特定数据库(mysql)。

This can be accomplished in your database by leveraging guarantees from your specific DB (mysql).

postgres / mysql的默认隔离级别允许2次并发读取以查看相同的数据,然后使每个覆盖另一个(

The default isolation level for postgres/mysql allow for 2 concurrent reads to see the same data, and then have each one overwrite the other (on a write).

postgres文档提供了这种情况的优秀示例

The postgres documentation provides an excellent example of this case:


由于上述规则,有可能进行更新命令到
会看到不一致的快照:它可以看到并发
更新命令对它试图更新的同一行的影响,但是
却看不到这些命令对其他行的影响数据库。
的这种行为使读已提交模式不适用于
涉及复杂搜索条件的命令。但是,这对于
的简单案例是正确的。例如,考虑使用
交易来更新银行余额,例如:

Because of the above rule, it is possible for an updating command to see an inconsistent snapshot: it can see the effects of concurrent updating commands on the same rows it is trying to update, but it does not see effects of those commands on other rows in the database. This behavior makes Read Committed mode unsuitable for commands that involve complex search conditions; however, it is just right for simpler cases. For example, consider updating bank balances with transactions like:



BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 12345;
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 7534;
COMMIT;




如果两个这样的事务同时尝试改变$ b $的余额b帐户12345,我们显然希望第二笔交易以
开头的帐户行的更新版本开始。因为每个命令都是
,仅影响预定行,所以让它看到该行的更新版本
不会造成任何麻烦的不一致。

If two such transactions concurrently try to change the balance of account 12345, we clearly want the second transaction to start with the updated version of the account's row. Because each command is affecting only a predetermined row, letting it see the updated version of the row does not create any troublesome inconsistency.

...


Read Committed模式提供的部分事务隔离对于许多应用程序来说都是
,并且这种模式对
而言使用起来非常快捷,简单;但是,这还不足以适用于所有情况。与$ Read $ Committed模式相比,执行
复杂查询和更新的应用程序可能需要更严格一致的数据库
视图。

The partial transaction isolation provided by Read Committed mode is adequate for many applications, and this mode is fast and simple to use; however, it is not sufficient for all cases. Applications that do complex queries and updates might require a more rigorously consistent view of the database than Read Committed mode provides.

这篇关于在Node.js中防止并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆