node.js - nodejs 高并发下请求同一资源
ringa_lee
ringa_lee 2017-04-17 13:18:46
0
2
563

问题描述:
举个例子,比如买票,数据库中只有一张票了,现在两个人同时购买这张票,请问nodejs是如何处理的?有人说,nodejs是单线程,不会产生此问题。那如果是利用多核多线程呢?或N台服务器,m个线程同时请求这个资源呢?感谢!

ringa_lee
ringa_lee

ringa_lee

reply all(2)
PHPzhong

This problem may occur for every ticket purchased, not just the last ticket. In addition, Node.js is single-threaded, so similar problems will not occur with stand-alone services, even with multi-core systems. However, if there are N servers running and using data from the same database, multiple processes are competing for resources.

If you want to solve this kind of problem simply, lock the table. If you want to handle this kind of problem more efficiently, you need to add some cache. If it is a high concurrency situation, you need to do some preliminary screening at the cache layer.

巴扎黑

The data is in the database. Correctness under high concurrency depends on the database, such as using optimistic locking and adding version numbers to the data.

select version,data from table;
update table set data = 1,version = version + 1 where version = X

Judge whether it is successful based on the affectedRows returned by the update, and then spit out the results to the front end.
Node itself only does request processing and forwarding of database commands. It is generally implemented with asynchronous callbacks. Multiple identical requests can be concurrently sent to the database in a single process. Generally, blocking methods are not used to request DB.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template