php solve the problem spike panic buying lottery and other large concurrent flow caused by the negative warehoused

 

We know sql database processing is a section of the process, assuming purchases of process is this:

sql1: merchandise inventory query


. 1
IF (stock number> 0 ) 2 { 3 // generating line 4 // Stock -1 . 5 >

 

When there is no concurrency, the above process seems so perfect, it is supposed that the two orders, and inventory only one, and phase two people in sql1 queries to the inventory is> 0, then eventually executed sql2, Finally inventory becomes -1, overbooking, and either fill inventory or customer complaints, etc. it.

To solve this problem the more popular ideas:

1. processing a queue with additional single process, single request into the queue, one by one treatment, there would be complicated by the problem, but to additional background processes and delays, not be considered.

2. The database optimistic locking, roughly meaning to check inventory, then flew inventory +1, then the order is generated, before update stock inventory query again to see if the expected number of stocks with consistent inconsistency on rollback insufficient to prompt the user inventory.

3. Judging update result, we can add a condition update judgment in sql2 time ... where stock> 0, if it returns false, it indicates lack of inventory, and roll back the transaction.

4. With exclusive lock file, the processing time in a single request, with a flock lock a file, if the lock fails illustrate the other order is being processed, then prompts the user to either wait or direct "server busy"

Herein it is to say fourth embodiment, roughly the following code:

Blocking (waiting) mode

<?php
$fp = fopen("lock.txt", "w+");
if(flock($fp,LOCK_EX))
{
  //..处理订单
  flock($fp,LOCK_UN);
}
fclose($fp);
?>

 

Non-blocking mode

? < PHP
 $ FP = the fopen ( "lock.txt", "W +" );
 IF ( Flock ( $ FP , LOCK_EX | the LOCK_NB)) 
{ 
  // .. process order 
  Flock ( $ FP , LOCK_UN); 
} 
the else 
{ 
  echo "The system is busy, please try again later" ; 
} 

fclose ( $ fp );
 ?>

 

 

 

Guess you like

Origin www.cnblogs.com/guiyishanren/p/11564256.html