我在 Nodejs(Express) 中构建了一个电子商务后端,假设有一个产品,只剩下 1 个数量 并且两个用户同时尝试购买该产品都在我的 Mysql Db 的数量部分中获得了该产品的负值
如何摆脱这个,建议会有帮助
谢谢
请您参考如下方法:
Database Transaction Isolation Levels
这可以通过利用特定数据库 (mysql) 的保证在您的数据库中完成。
postgres/mysql 的默认隔离级别允许 2 个并发读取以查看相同的数据,然后让每个读取覆盖另一个(在写入时)。
postgres 文档提供了一个 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;
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.
...
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.