高併發處理【電商搶購】

  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. }  
  54. ?>  


優化方案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');  
  12. ?>  

搶購、描述邏輯
  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. }   

模擬5000高併發測試
webbench -c 5000 -t 60 http://192.168.1.198/big/index.php
ab -r -n 6000 -c 5000  http://192.168.1.198/big/index.php


上述只是簡單模擬高併發下的搶購,真實場景要比這複雜很多,很多注意的地方
如搶購頁面做成靜態的,通過ajax調用接口
再如上面的會導致一個用戶搶多個,思路:
需要一個排隊隊列和搶購結果隊列及庫存隊列。高併發情況,先將用戶進入排隊隊列,用一個線程循環處理從排隊隊列取出一個用戶,判斷用戶是否已在搶購結果隊列,如果在,則已搶購,否則未搶購,庫存減1,寫數據庫,將用戶入結果隊列。


測試數據表

  1. --  
  2. -- 數據庫: `big`  
  3. --  
  4.   
  5. -- --------------------------------------------------------  
  6.   
  7. --  
  8. -- 表的結構 `ih_goods`  
  9. --  
  10.   
  11.   
  12. CREATE TABLE IF NOT EXISTS `ih_goods` (  
  13.   `goods_id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
  14.   `cat_id` int(11) NOT NULL,  
  15.   `goods_name` varchar(255) NOT NULL,  
  16.   PRIMARY KEY (`goods_id`)  
  17. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;  
  18.   
  19.   
  20. --  
  21. -- 轉存表中的數據 `ih_goods`  
  22. --  
  23.   
  24.   
  25. INSERT INTO `ih_goods` (`goods_id`, `cat_id`, `goods_name`) VALUES  
  26. (1, 0, '小米手機');  
  27.   
  28. -- --------------------------------------------------------  
  29.   
  30. --  
  31. -- 表的結構 `ih_log`  
  32. --  
  33.   
  34. CREATE TABLE IF NOT EXISTS `ih_log` (  
  35.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  36.   `event` varchar(255) NOT NULL,  
  37.   `type` tinyint(4) NOT NULL DEFAULT '0',  
  38.   `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  
  39.   PRIMARY KEY (`id`)  
  40. ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;  
  41.   
  42. --  
  43. -- 轉存表中的數據 `ih_log`  
  44. --  
  45.   
  46.   
  47. -- --------------------------------------------------------  
  48.   
  49. --  
  50. -- 表的結構 `ih_order`  
  51. --  
  52.   
  53. CREATE TABLE IF NOT EXISTS `ih_order` (  
  54.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  55.   `order_sn` char(32) NOT NULL,  
  56.   `user_id` int(11) NOT NULL,  
  57.   `status` int(11) NOT NULL DEFAULT '0',  
  58.   `goods_id` int(11) NOT NULL DEFAULT '0',  
  59.   `sku_id` int(11) NOT NULL DEFAULT '0',  
  60.   `price` float NOT NULL,  
  61.   `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  
  62.   PRIMARY KEY (`id`)  
  63. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='訂單表' AUTO_INCREMENT=1 ;  
  64.   
  65. --  
  66. -- 轉存表中的數據 `ih_order`  
  67. --  
  68.   
  69.   
  70. -- --------------------------------------------------------  
  71.   
  72. --  
  73. -- 表的結構 `ih_store`  
  74. --  
  75.   
  76. CREATE TABLE IF NOT EXISTS `ih_store` (  
  77.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  78.   `goods_id` int(11) NOT NULL,  
  79.   `sku_id` int(10) unsigned NOT NULL DEFAULT '0',  
  80.   `number` int(10) NOT NULL DEFAULT '0',  
  81.   `freez` int(11) NOT NULL DEFAULT '0' COMMENT '虛擬庫存',  
  82.   PRIMARY KEY (`id`)  
  83. ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='庫存' AUTO_INCREMENT=2 ;  
  84.   
  85. --  
  86. -- 轉存表中的數據 `ih_store`  
  87. --  
  88.   
  89. INSERT INTO `ih_store` (`id`, `goods_id`, `sku_id`, `number`, `freez`) VALUES  
  90. (1, 1, 11, 500, 0); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章