Home  >  Article  >  Backend Development  >  How does php handle high concurrency?

How does php handle high concurrency?

王林
王林Original
2019-09-24 17:54:003696browse

How does php handle high concurrency?

Data security under high concurrency

We know that when multiple threads write to the same file, "thread safety" will exist (Multiple threads run the same piece of code at the same time. If the result of each run is the same as that of a single-thread run, and the result is the same as expected, it is thread-safe). If it is a MySQL database, you can use its own lock mechanism to solve the problem. However, in large-scale concurrency scenarios, MySQL is not recommended.

In flash sales and rush sales scenarios, there is another problem, which is "over-sending". If this aspect is not controlled carefully, excessive sending will occur. We have also heard that some e-commerce companies conduct rush buying activities. After the buyer successfully purchases the product, the merchant does not recognize the order as valid and refuses to deliver the goods. The problem here may not necessarily be that the merchant is treacherous, but that it is caused by the risk of over-issuance at the technical level of the system.

1. Reasons for over-delivery

Assume that in a certain rush-buying scenario, we only have 100 products in total, and at the last moment, we have consumed 99 products. Only the last one remains. At this time, the system sent multiple concurrent requests. The product balances read by these requests were all 99, and then they all passed this balance judgment, which eventually led to over-issuance. (Same as the scene mentioned earlier in the article)

How does php handle high concurrency?

In the picture above, it resulted in concurrent user B also "successfully buying", allowing one more person to obtain the product. This scenario is very easy to occur in high concurrency situations.

Optimization plan 1: Set the inventory field number field to unsigned. When the inventory is 0, because the field cannot be a negative number, false will be returned

<?php
//优化方案1:将库存字段number字段设为unsigned,当库存为0时,因为字段不能为负数,将会返回false
include(&#39;./mysql.php&#39;);
$username = &#39;wang&#39;.rand(0,1000);
//生成唯一订单
function build_order_no(){
  return date(&#39;ymd&#39;).substr(implode(NULL, array_map(&#39;ord&#39;, str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
//记录日志
function insertLog($event,$type=0,$username){
    global $conn;
    $sql="insert into ih_log(event,type,usernma)
    values(&#39;$event&#39;,&#39;$type&#39;,&#39;$username&#39;)";
    return mysqli_query($conn,$sql);
}
function insertOrder($order_sn,$user_id,$goods_id,$sku_id,$price,$username,$number)
{
      global $conn;
      $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price,username,number)
      values(&#39;$order_sn&#39;,&#39;$user_id&#39;,&#39;$goods_id&#39;,&#39;$sku_id&#39;,&#39;$price&#39;,&#39;$username&#39;,&#39;$number&#39;)";
     return  mysqli_query($conn,$sql);
}
//模拟下单操作
//库存是否大于0
$sql="select number from ih_store where goods_id=&#39;$goods_id&#39; and sku_id=&#39;$sku_id&#39; ";
$rs=mysqli_query($conn,$sql);
$row = $rs->fetch_assoc();
  if($row[&#39;number&#39;]>0){//高并发下会导致超卖
      if($row[&#39;number&#39;]<$number){
        return insertLog(&#39;库存不够&#39;,3,$username);
      }
      $order_sn=build_order_no();
      //库存减少
      $sql="update ih_store set number=number-{$number} where sku_id=&#39;$sku_id&#39; and number>0";
      $store_rs=mysqli_query($conn,$sql);
      if($store_rs){
          //生成订单
          insertOrder($order_sn,$user_id,$goods_id,$sku_id,$price,$username,$number);
          insertLog(&#39;库存减少成功&#39;,1,$username);
      }else{
          insertLog(&#39;库存减少失败&#39;,2,$username);
      }
  }else{
      insertLog(&#39;库存不够&#39;,3,$username);
  }
?>

2. The idea of ​​file lock

For applications where the daily IP is not high or the number of concurrency is not very large, generally there is no need to consider these! There is no problem at all with normal file manipulation methods. But if the concurrency is high, when we read and write files, it is very likely that multiple processes will operate on the next file. If the access to the file is not exclusive at this time, it will easily cause data loss.

Optimization 4: Use non-blocking file exclusive lock

<?php
//优化方案4:使用非阻塞的文件排他锁
include (&#39;./mysql.php&#39;);
//生成唯一订单号
function build_order_no(){
  return date(&#39;ymd&#39;).substr(implode(NULL, array_map(&#39;ord&#39;, str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
//记录日志
function insertLog($event,$type=0){
    global $conn;
    $sql="insert into ih_log(event,type)
    values(&#39;$event&#39;,&#39;$type&#39;)";
    mysqli_query($conn,$sql);
}
$fp = fopen("lock.txt", "w+");
if(!flock($fp,LOCK_EX | LOCK_NB)){
    echo "系统繁忙,请稍后再试";
    return;
}
//下单
$sql="select number from ih_store where goods_id=&#39;$goods_id&#39; and sku_id=&#39;$sku_id&#39;";
$rs =  mysqli_query($conn,$sql);
$row = $rs->fetch_assoc();
if($row[&#39;number&#39;]>0){//库存是否大于0
    //模拟下单操作
    $order_sn=build_order_no();
    $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price)
    values(&#39;$order_sn&#39;,&#39;$user_id&#39;,&#39;$goods_id&#39;,&#39;$sku_id&#39;,&#39;$price&#39;)";
    $order_rs =  mysqli_query($conn,$sql);
    //库存减少
    $sql="update ih_store set number=number-{$number} where sku_id=&#39;$sku_id&#39;";
    $store_rs =  mysqli_query($conn,$sql);
    if($store_rs){
      echo &#39;库存减少成功&#39;;
        insertLog(&#39;库存减少成功&#39;);
        flock($fp,LOCK_UN);//释放锁
    }else{
      echo &#39;库存减少失败&#39;;
        insertLog(&#39;库存减少失败&#39;);
    }
}else{
  echo &#39;库存不够&#39;;
    insertLog(&#39;库存不够&#39;);
}
fclose($fp);
 ?>

Recommended tutorial: PHP video tutorial

The above is the detailed content of How does php handle high concurrency?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn