Reprint Address: Click to open the link
We know that database processing of SQL is a matter of processing, assuming that the process of buying goods is this:
SQL1: Check Product Inventory
if (Qty > 0 in stock)
{
Generate Order ...
SQL2: Stock-1
}
When there is no concurrency, the above process seems to be so perfect, assuming that at the same time two people order, and inventory only 1, in the SQL1 stage two people to check the inventory is >0, and eventually executed the SQL2, inventory finally changed into-1, oversold, or fill inventory, or other user complaints.
To solve this problem more popular ideas:
1. With an additional single process to process a queue, placing a single request in the queue, one after another, there will be no concurrency problem, but the additional background process and delay issues, not considered.
2. Database optimistic lock, the general meaning is to check the inventory first, then immediately put inventory +1, and then after the order is generated, in the inventory before the update to check the inventory, to see if the expected inventory quantity is consistent, inconsistent roll back, prompting the user inventory is insufficient.
3. According to the update results, we can add a judgment condition at the time of SQL2 update ... where inventory >0, if False, indicates that the inventory is insufficient and the transaction is rolled back.
4. With the use of file exclusive lock, when processing the order request, with flock lock a file, if the lock failure indicates that there are other orders being processed, at this time either wait or prompt the user "server Busy"
This article is to say the 4th scenario, the approximate code is as follows:
Block (wait) mode
?
1 2 3 4 5 6 7 8 9 |
$fp = fopen ( "lock.txt" , "w+" );
if ( flock ( $fp ,LOCK_EX))
{
//..处理订单
flock ( $fp ,LOCK_UN);
}
fclose( $fp );
|
//non-blocking mode
?
1 2 3 4 5 6 7 8 9 12 |
!--? php $fp = fopen ( "Lock.txt" , "w+" ); if ( flock ( $fp , LOCK_EX | LOCK_NB) { //. Processing orders flock ( $fp , lock_un); } Else { echo "The system is busy, please try again later" ; } fclose ( $fp ); |
In which way, look at the number of concurrent.
The above describes the PHP solution to the next order, the lottery concurrency caused by negative inventory, including the content, I hope that the PHP tutorial interested in a friend helpful.