php結合redis實現高併發下的搶購、秒殺功能

搶購、秒殺是日常很常見的場景,面試的時候面試官也常常會問到,好比問你淘寶中的搶購秒殺是怎麼實現的等等。php

搶購、秒殺實現很簡單,可是有些問題須要解決,主要針對兩個問題:mysql

1 高併發對數據庫產生的壓力面試

2 競爭狀態下如何解決庫存的正確減小("超賣"問題)ajax

第一個問題,對於PHP來講很簡單,用緩存技術就能夠緩解數據庫壓力,好比memcache,redis等緩存技術。redis

第二個問題就比較複雜點:sql

常規寫法:數據庫

查詢出對應商品的庫存,看是否大於0,而後執行生成訂單等操做,可是在判斷庫存是否大於0處,若是在高併發下就會有問題,致使庫存量出現負數緩存

 

 1 <?php
 2 $conn=mysql_connect("localhost","big","123456"); 
 3 if(!$conn){ 
 4     echo "connect failed"; 
 5     exit; 
 6 } 
 7 mysql_select_db("big",$conn); 
 8 mysql_query("set names utf8");
 9  
10 $price=10;
11 $user_id=1;
12 $goods_id=1;
13 $sku_id=11;
14 $number=1;
15  
16 //生成惟一訂單
17 function build_order_no(){
18   return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
19 }
20 //記錄日誌
21 function insertLog($event,$type=0){
22     global $conn;
23     $sql="insert into ih_log(event,type) 
24     values('$event','$type')"; 
25     mysql_query($sql,$conn); 
26 }
27  
28 //模擬下單操做
29 //庫存是否大於0
30 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'";//解鎖 此時ih_store數據中goods_id='$goods_id' and sku_id='$sku_id' 的數據被鎖住(注3),其它事務必須等待這次事務 提交後才能執行
31 $rs=mysql_query($sql,$conn);
32 $row=mysql_fetch_assoc($rs);
33 if($row['number']>0){//高併發下會致使超賣
34     $order_sn=build_order_no();
35     //生成訂單 
36     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) 
37     values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; 
38     $order_rs=mysql_query($sql,$conn); 
39      
40     //庫存減小
41     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";
42     $store_rs=mysql_query($sql,$conn); 
43     if(mysql_affected_rows()){ 
44         insertLog('庫存減小成功');
45     }else{ 
46         insertLog('庫存減小失敗');
47     } 
48 }else{
49     insertLog('庫存不夠');
50 }

 

出現這種狀況怎麼辦呢?來看幾種優化方法:併發

優化方案1:將庫存字段number字段設爲unsigned,當庫存爲0時,由於字段不能爲負數,將會返回false高併發

1 //庫存減小
2 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id' and number>0";
3 $store_rs=mysql_query($sql,$conn); 
4 if(mysql_affected_rows()){ 
5     insertLog('庫存減小成功');
6 }

優化方案2:使用MySQL的事務,鎖住操做的行

 1 <?php
 2 $conn=mysql_connect("localhost","big","123456"); 
 3 if(!$conn){ 
 4     echo "connect failed"; 
 5     exit; 
 6 } 
 7 mysql_select_db("big",$conn); 
 8 mysql_query("set names utf8");
 9  
10 $price=10;
11 $user_id=1;
12 $goods_id=1;
13 $sku_id=11;
14 $number=1;
15  
16 //生成惟一訂單號
17 function build_order_no(){
18   return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
19 }
20 //記錄日誌
21 function insertLog($event,$type=0){
22     global $conn;
23     $sql="insert into ih_log(event,type) 
24     values('$event','$type')"; 
25     mysql_query($sql,$conn); 
26 }
27  
28 //模擬下單操做
29 //庫存是否大於0
30 mysql_query("BEGIN");   //開始事務
31 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id' FOR UPDATE";//此時這條記錄被鎖住,其它事務必須等待這次事務提交後才能執行
32 $rs=mysql_query($sql,$conn);
33 $row=mysql_fetch_assoc($rs);
34 if($row['number']>0){
35     //生成訂單 
36     $order_sn=build_order_no(); 
37     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) 
38     values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; 
39     $order_rs=mysql_query($sql,$conn); 
40      
41     //庫存減小
42     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";
43     $store_rs=mysql_query($sql,$conn); 
44     if(mysql_affected_rows()){ 
45         insertLog('庫存減小成功');
46         mysql_query("COMMIT");//事務提交即解鎖
47     }else{ 
48         insertLog('庫存減小失敗');
49     }
50 }else{
51     insertLog('庫存不夠');
52     mysql_query("ROLLBACK");
53 }

優化方案3:使用非阻塞的文件排他鎖

 1 <?php
 2 $conn=mysql_connect("localhost","root","123456"); 
 3 if(!$conn){ 
 4     echo "connect failed"; 
 5     exit; 
 6 } 
 7 mysql_select_db("big-bak",$conn); 
 8 mysql_query("set names utf8");
 9  
10 $price=10;
11 $user_id=1;
12 $goods_id=1;
13 $sku_id=11;
14 $number=1;
15  
16 //生成惟一訂單號
17 function build_order_no(){
18   return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
19 }
20 //記錄日誌
21 function insertLog($event,$type=0){
22     global $conn;
23     $sql="insert into ih_log(event,type) 
24     values('$event','$type')"; 
25     mysql_query($sql,$conn); 
26 }
27  
28 $fp = fopen("lock.txt", "w+");
29 if(!flock($fp,LOCK_EX | LOCK_NB)){
30     echo "系統繁忙,請稍後再試";
31     return;
32 }
33 //下單
34 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'";
35 $rs=mysql_query($sql,$conn);
36 $row=mysql_fetch_assoc($rs);
37 if($row['number']>0){//庫存是否大於0
38     //模擬下單操做 
39     $order_sn=build_order_no(); 
40     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) 
41     values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; 
42     $order_rs=mysql_query($sql,$conn); 
43      
44     //庫存減小
45     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";
46     $store_rs=mysql_query($sql,$conn); 
47     if(mysql_affected_rows()){ 
48         insertLog('庫存減小成功');
49         flock($fp,LOCK_UN);//釋放鎖
50     }else{ 
51         insertLog('庫存減小失敗');
52     } 
53 }else{
54     insertLog('庫存不夠');
55 }
56 fclose($fp);

優化方案4:使用redis隊列,由於pop操做是原子的,即便有不少用戶同時到達,也是依次執行,推薦使用(mysql事務在高併發下性能降低很厲害,文件鎖的方式也是)

先將商品庫存如隊列

 1 <?php
 2 $store=1000;
 3 $redis=new Redis();
 4 $result=$redis->connect('127.0.0.1',6379);
 5 $res=$redis->llen('goods_store');
 6 echo $res;
 7 $count=$store-$res;
 8 for($i=0;$i<$count;$i++){
 9     $redis->lpush('goods_store',1);
10 }
11 echo $redis->llen('goods_store');

搶購、描述邏輯

 1 <?php
 2 $conn=mysql_connect("localhost","big","123456"); 
 3 if(!$conn){ 
 4     echo "connect failed"; 
 5     exit; 
 6 } 
 7 mysql_select_db("big",$conn); 
 8 mysql_query("set names utf8");
 9  
10 $price=10;
11 $user_id=1;
12 $goods_id=1;
13 $sku_id=11;
14 $number=1;
15  
16 //生成惟一訂單號
17 function build_order_no(){
18   return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
19 }
20 //記錄日誌
21 function insertLog($event,$type=0){
22     global $conn;
23     $sql="insert into ih_log(event,type) 
24     values('$event','$type')"; 
25     mysql_query($sql,$conn); 
26 }
27  
28 //模擬下單操做
29 //下單前判斷redis隊列庫存量
30 $redis=new Redis();
31 $result=$redis->connect('127.0.0.1',6379);
32 $count=$redis->lpop('goods_store');
33 if(!$count){
34     insertLog('error:no store redis');
35     return;
36 }
37  
38 //生成訂單 
39 $order_sn=build_order_no();
40 $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) 
41 values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; 
42 $order_rs=mysql_query($sql,$conn); 
43  
44 //庫存減小
45 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";
46 $store_rs=mysql_query($sql,$conn); 
47 if(mysql_affected_rows()){ 
48     insertLog('庫存減小成功');
49 }else{ 
50     insertLog('庫存減小失敗');
51 }

上述只是簡單模擬高併發下的搶購,真實場景要比這複雜不少,不少注意的地方

如搶購頁面作成靜態的,經過ajax調用接口

再如上面的會致使一個用戶搶多個,思路:

須要一個排隊隊列和搶購結果隊列及庫存隊列。高併發狀況,先將用戶進入排隊隊列,用一個線程循環處理從排隊隊列取出一個用戶,判斷用戶是否已在搶購結果隊列,若是在,則已搶購,不然未搶購,庫存減1,寫數據庫,將用戶入結果隊列。

我之間作商城項目的時候,在秒殺這一塊我直接用的redis,這段時間看了看上面的幾種方法,雖然各有不一樣,可是實現目的都同樣的,各位本身選擇,開心就好。

相關文章
相關標籤/搜索