PHP和Redis實現在高併發下的搶購及秒殺功能
搶購、秒殺是平常很常見的場景,面試的時候面試官也經常會問到,比如問你淘寶中的搶購秒殺是怎麼實現的等等。
搶購、秒殺實現很簡單,但是有些問題需要解決,主要針對兩個問題:
一、高併發對資料庫產生的壓力
二、競爭狀態下如何解決庫存的正確減少("超賣"問題)
第一個問題,對於PHP來說很簡單,用快取技術就可以緩解資料庫壓力,比如memcache,redis等快取技術。
第二個問題就比較複雜點:
常規寫法:
查詢出對應商品的庫存,看是否大於0,然後執行生成訂單等操作,但是在判斷庫存是否大於0處,如果在高併發下就會有問題,導致庫存量出現負數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <?php $conn=mysql_connect("localhost","big","123456"); if(!$conn){ echo "connect failed"; exit; } mysql_select_db("big",$conn); mysql_query("set names utf8"); $price=10; $user_id=1; $goods_id=1; $sku_id=11; $number=1; //生成唯一訂單 function build_order_no(){ return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } //記錄日誌 function insertLog($event,$type=0){ global $conn; $sql="insert into ih_log(event,type) values('$event','$type')"; mysql_query($sql,$conn); } //模擬下單操作 //庫存是否大於0 $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),其它事務必須等待此次事務 提交後才能執行 $rs=mysql_query($sql,$conn); $row=mysql_fetch_assoc($rs); if($row['number']>0){//高併發下會導致超賣 $order_sn=build_order_no(); //生成訂單 $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; $order_rs=mysql_query($sql,$conn); //庫存減少 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'"; $store_rs=mysql_query($sql,$conn); if(mysql_affected_rows()){ insertLog('庫存減少成功'); }else{ insertLog('庫存減少失敗'); } }else{ insertLog('庫存不夠'); } |
出現這種情況怎麼辦呢?來看幾種優化方法:
優化方案1:將庫存欄位number欄位設為unsigned,當庫存為0時,因為欄位不能為負數,將會返回false
1 2 3 4 5 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <?php $conn=mysql_connect("localhost","big","123456"); if(!$conn){ echo "connect failed"; exit; } mysql_select_db("big",$conn); mysql_query("set names utf8"); $price=10; $user_id=1; $goods_id=1; $sku_id=11; $number=1; //生成唯一訂單號 function build_order_no(){ return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } //記錄日誌 function insertLog($event,$type=0){ global $conn; $sql="insert into ih_log(event,type) values('$event','$type')"; mysql_query($sql,$conn); } //模擬下單操作 //庫存是否大於0 mysql_query("BEGIN"); //開始事務 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id' FOR UPDATE";//此時這條記錄被鎖住,其它事務必須等待此次事務提交後才能執行 $rs=mysql_query($sql,$conn); $row=mysql_fetch_assoc($rs); if($row['number']>0){ //生成訂單 $order_sn=build_order_no(); $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; $order_rs=mysql_query($sql,$conn); //庫存減少 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'"; $store_rs=mysql_query($sql,$conn); if(mysql_affected_rows()){ insertLog('庫存減少成功'); mysql_query("COMMIT");//事務提交即解鎖 }else{ insertLog('庫存減少失敗'); } }else{ insertLog('庫存不夠'); mysql_query("ROLLBACK"); } |
優化方案3:使用非阻塞的檔案排他鎖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <?php $conn=mysql_connect("localhost","root","123456"); if(!$conn){ echo "connect failed"; exit; } mysql_select_db("big-bak",$conn); mysql_query("set names utf8"); $price=10; $user_id=1; $goods_id=1; $sku_id=11; $number=1; //生成唯一訂單號 function build_order_no(){ return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } //記錄日誌 function insertLog($event,$type=0){ global $conn; $sql="insert into ih_log(event,type) values('$event','$type')"; mysql_query($sql,$conn); } $fp = fopen("lock.txt", "w+"); if(!flock($fp,LOCK_EX | LOCK_NB)){ echo "系統繁忙,請稍後再試"; return; } //下單 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'"; $rs=mysql_query($sql,$conn); $row=mysql_fetch_assoc($rs); if($row['number']>0){//庫存是否大於0 //模擬下單操作 $order_sn=build_order_no(); $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; $order_rs=mysql_query($sql,$conn); //庫存減少 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'"; $store_rs=mysql_query($sql,$conn); if(mysql_affected_rows()){ insertLog('庫存減少成功'); flock($fp,LOCK_UN);//釋放鎖 }else{ insertLog('庫存減少失敗'); } }else{ insertLog('庫存不夠'); } fclose($fp); |
優化方案4:使用redis佇列,因為pop操作是原子的,即使有很多使用者同時到達,也是依次執行,推薦使用(mysql事務在高併發下效能下降很厲害,檔案鎖的方式也是)
先將商品庫存如佇列
1 2 3 4 5 6 7 8 9 10 11 | <?php $store=1000; $redis=new Redis(); $result=$redis->connect('127.0.0.1',6379); $res=$redis->llen('goods_store'); echo $res; $count=$store-$res; for($i=0;$i<$count;$i++){ $redis->lpush('goods_store',1); } echo $redis->llen('goods_store'); |
搶購、描述邏輯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <?php $conn=mysql_connect("localhost","big","123456"); if(!$conn){ echo "connect failed"; exit; } mysql_select_db("big",$conn); mysql_query("set names utf8"); $price=10; $user_id=1; $goods_id=1; $sku_id=11; $number=1; //生成唯一訂單號 function build_order_no(){ return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } //記錄日誌 function insertLog($event,$type=0){ global $conn; $sql="insert into ih_log(event,type) values('$event','$type')"; mysql_query($sql,$conn); } //模擬下單操作 //下單前判斷redis佇列庫存量 $redis=new Redis(); $result=$redis->connect('127.0.0.1',6379); $count=$redis->lpop('goods_store'); if(!$count){ insertLog('error:no store redis'); return; } //生成訂單 $order_sn=build_order_no(); $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; $order_rs=mysql_query($sql,$conn); //庫存減少 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'"; $store_rs=mysql_query($sql,$conn); if(mysql_affected_rows()){ insertLog('庫存減少成功'); }else{ insertLog('庫存減少失敗'); } |
上述只是簡單模擬高併發下的搶購,真實場景要比這複雜很多,很多注意的地方,如搶購頁面做成靜態的,通過ajax呼叫介面。
Redis 列表命令
http://www.runoob.com/redis/redis-lists.html
再如上面的會導致一個使用者搶多個,思路:
需要一個排隊佇列和搶購結果佇列及庫存佇列。高併發情況,先將使用者進入排隊佇列,用一個執行緒迴圈處理從排隊佇列取出一個使用者,判斷使用者是否已在搶購結果佇列,如果在,則已搶購,否則未搶購,庫存減1,寫資料庫,將使用者入結果佇列。
我之間做商城專案的時候,在秒殺這一塊我直接用的redis,這段時間看了看上面的幾種方法,雖然各有不同,但是實現目的都一樣的,各位自己選擇,開心就