high concurrency php solutions (for buying)

Recently doing a group purchase project encountered a problem is when to buy, spike, sweepstakes and other activities, a limited number of stocks, but at the same time the number of orders exceeds the number of stocks, commodities will lead to overbooking problem. So how do we solve this problem, my ideas are as follows: 

sql1: Query merchandise inventory
if (stock number> 0)
{
  // ... generate orders
  SQL2: Stock -1
}

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. additional treatment with a single process queue, the next 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 is to say fourth embodiment, roughly the following code:
block (wait) mode
 
<PHP?
$ FP = the fopen ( "lock.txt", "W +");
IF (Flock ($ FP, LOCK_EX)) // lock current pointer ,,,
{
  // .. process order
  Flock ($ FP, LOCK_UN);
}
fclose ($ FP);
?>
nonblocking
 
? <PHP
$ FP = the fopen ( "lock.txt", "W +" );
IF (Flock ($ fp, LOCK_EX | LOCK_NB))
{
  // .. process orders
  Flock ($ fp, LOCK_UN);
}
the else
{
  echo "system is busy, please try again later";
}
 
fclose ($ fp) ;
?> https://blog.csdn.net/luguoit/article/details/46620095

Guess you like

Origin blog.csdn.net/m0_37477061/article/details/91476697