This paper introduces several methods to solve the concurrency problem in PHP development, and share it for everyone's reference.
For commodity snapping and other concurrent scenarios, there may be oversold phenomenon, it is necessary to solve these problems caused by concurrency
There is no native solution for concurrency in the PHP language, so there are other ways to implement concurrency control.
Scenario One: Use file lock to lock it
The Flock function is used to get the lock of the file, which can only be obtained by one thread, and the other thread that does not acquire the lock either blocks or gets the failure
When acquiring the lock, check the inventory first, if the inventory is greater than 0, then the order operation, reduce inventory, and then release the lock
Scenario two: Using pessimistic locks provided by the MySQL database
The InnoDB storage engine supports row-level locks, and when a row of data is locked, other processes cannot manipulate this row of data
Query and lock the row first:
Select Stock_num from table where id=1 for update if (Stock_num > 0) { //place Order Update table set Stock_num=stock -1 where id=1}
Scenario Three: Using queues
Store the user's order request in one queue, and the background uses a separate process to process the order request in the queue
Scenario Four: Using Redis
Redis operations are atomic, you can put the inventory of goods into Redis, before the order to DECR operations on inventory, if the return value is greater than or equal to 0 can place orders, otherwise it is not possible to place orders, this way more efficient
if (Redis->get (' stock_num ') > 0) {stock_num = REDIS->DECR (' Stock_num ') if (stock_num >= 0) {//Place order}else{//Low Inventory }}else{//Insufficient Stock}
Other concurrency issues:
In real-world applications, in many cases the data will be cached, when the cache fails, go to the database to fetch data and reset the cache, if the concurrency is very large, there will be many processes at the same time to the database to fetch data, resulting in many requests
Penetrate to the database, and make the database crash, here can be used to solve the file lock
$data = $cache->get (' key '), if (! $data) { $fp = fopen (' lockfile '); if (Flock ($FP, lock_ex)) { $data = $cache->get (' key ');//Check the cache again after you get the lock, you may already have the if (! $data) { $data = mysql- >query (); $cache->set (' key ', $data); } Flock ($FP, lock_un); } Fclose ($FP);}
Frankly speaking, to solve concurrency problems must be locked, the nature of the various programs are locked
Related reading:
MySQL Redis Learning and application
A method of implementing transaction mechanism and optimistic locking in Redis
MySQL database Optimization (iii)-mysql pessimistic lock and optimistic lock (concurrency control)