We know that database processing SQL is processed one by one. Assume that the process of purchasing goods is as follows:
sql1: Query product inventory
if(库存数量 > 0) { //生成订单... sql2:库存-1 }
When there is no concurrency, the above process looks so perfect. Suppose two people place orders at the same time, and there is only 1 inventory. In the sql1 stage, the inventory queried by both people is >0, so in the end both After executing sql2, the inventory finally became -1, indicating that it was oversold. Either replenish the inventory or wait for user complaints.
The more popular ideas to solve this problem:
1. Use an additional single process to process a queue, place order requests in the queue, and process them one by one, so there will be no concurrency issues. However, additional background processes and delay issues will not be considered.
2. Database optimistic locking, which roughly means querying the inventory first, then immediately adding 1 to the inventory, and then after the order is generated, query the inventory again before updating the inventory to see if it is consistent with the expected inventory quantity. It rolls back and prompts the user that the inventory is insufficient.
3. Judging based on the update results, we can add a judgment condition update...where inventory>0 in sql2. If false is returned, it means that the inventory is insufficient and the transaction will be rolled back.
4. With the help of file exclusive lock, when processing an order request, use flock to lock a file. If the lock fails, it means that other orders are being processed. At this time, either wait or directly prompt the user "server busy"
This article is going to talk about the 4th solution. The approximate code is as follows:
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 = fopen("lock.txt", "w+"); if(flock($fp,LOCK_EX | LOCK_NB)) { //..处理订单 flock($fp,LOCK_UN); } else { echo "系统繁忙,请稍后再试"; } fclose($fp); ?>