php+redis實現搶購功能

來源:互聯網
上載者:User
前面我們和大家分享了php和redis實現商城秒殺功能代碼分享,本文主要為大家詳細介紹了php+redis訊息佇列搶購實現代碼,具有一定的參考價值,感興趣的小夥伴們可以參考一下,希望能協助到大家。

實現功能:

1. 基於redis隊列,防止高並發的超賣
2. 基於mysql的事務加排它鎖,防止高並發的超賣

基於redis隊列工作流程:

1. 管理員根據goods表中的庫存,建立redis商品庫存隊列
2. 用戶端訪問秒殺API
3. web伺服器先從redis的商品庫存隊列中查詢剩餘庫存重點內容
4. redis隊列中有剩餘,則在mysql中建立訂單,去庫存,搶購成功
5. redis隊列中沒有剩餘,則提示庫存不足,搶購失敗重點內容

基於mysql事務和排它鎖工作流程:

1. 開啟事務
2. 查詢庫存,並顯示的設定寫鎖(獨佔鎖定):SELECT * FROM goods WHERE id = 1 FOR UPDATE
3. 產生訂單
4. 去庫存,隱示的設定寫鎖(獨佔鎖定):UPDATE goods SET counts = counts – 1 WHERE id = 1
5. commit,釋放鎖

注意:第二步步可以設定共用鎖定,不然有可能會造成死結。

代碼:


<?php/*********************************************** 搶購模組** @author liubin* @date 2016-02-10** ab -n 1000 -c 100 http://192.168.16.73/Seckill/buy.php**/class seckill extends common{ private $_orderModel = null; private $_goodsModel = null; private $_redis = null; /*  * 錯誤資訊 */ protected $_error = ''; /**  * 構造器  * */ public function __construct() {  if($this->_orderModel === null){   $this->_orderModel = new OrderModel();  }  if($this->_goodsModel === null){   $this->_goodsModel = new GoodsModel();  }  if($this->_redis === null){   $this->_redis = new QRedis();   } } /*  * 秒殺API  *   * @author liubin  * @date 2017-02-10 */ public function addQsec(){  $gid = intval($_GET['gid']);  $type = isset($_GET['type']) ? $_GET['type'] : 'mysql';  switch ($type) {   case 'mysql':    $this->order_check_mysql($gid);    echo $this->getError();    break;   case 'redis':    $this->order_check_redis($gid);    echo $this->getError();    break;   case 'transaction':    $this->order_check_transaction($gid);    echo $this->getError();    break;   default:    echo '類型錯誤';    break;  } } /*  * 擷取錯誤資訊  *   * @author liubin  * @date 2017-02-10 */ public function getError(){  return $this->_error; } /*  * 基於mysql驗證庫存資訊  * @desc 高並發下會導致超賣  *  * @author liubin  * @date 2017-02-10 */ protected function order_check_mysql($gid){  $model = $this->_goodsModel;  $pdo = $model->getHandler();  $gid = intval($gid);  /*   * 1:$sql_forlock如果不加事務,不加寫鎖:   * 超賣非常嚴重,就不說了   *    * 2:$sql_forlock如果不加事務,只加寫鎖:   * 第一個會話讀$sql_forlock時加寫鎖,第一個會話$sql_forlock查詢結束會釋放該行鎖.   * 第二個會話在第一個會話釋放後讀$sql_forlock的寫鎖時,會再次$sql_forlock查庫存   * 導致超賣現象產生   *  */  $sql_forlock = 'select * from goods where id = '.$gid .' limit 1 for update';  //$sql_forlock = 'select * from goods where id = '.$gid .' limit 1';  $result = $pdo->query($sql_forlock,PDO::FETCH_ASSOC);  $goodsInfo = $result->fetch();  if($goodsInfo['counts']>0){   //去庫存   $gid = $goodsInfo['id'];   $sql_inventory = 'UPDATE goods SET counts = counts - 1 WHERE id = '.$gid;   $result = $this->_goodsModel->exect($sql_inventory);   if($result){    //創訂單    $data    = [];    $data['order_id'] = $this->_orderModel->buildOrderNo();    $data['goods_id'] = $goodsInfo['id'];    $data['addtime'] = time();    $data['uid']  = 1;    $order_rs = $this->_orderModel->create_order($data);    if($order_rs){     $this->_error = '購買成功';     return true;    }   }  }  $this->_error = '庫存不足';  return false; } /*  * 基於redis隊列驗證庫存資訊  * @desc Redis是底層是單線程的,命令執行是原子操作,包括lpush,lpop等.高並發下不會導致超賣  *  * @author liubin  * @date 2017-02-10 */ protected function order_check_redis($gid){  $goodsInfo = $this->_goodsModel->getGoods($gid);  if(!$goodsInfo){   $this->_error = '商品不存在';   return false;  }  $key = 'goods_list_'.$goodsInfo['id'];  $count = $this->_redis->getHandel()->lpop($key);  if(!$count){   $this->_error = '庫存不足';   return false;  }  //產生訂單  $data    = [];  $data['order_id'] = $this->_orderModel->buildOrderNo();  $data['goods_id'] = $goodsInfo['id'];  $data['addtime'] = time();  $data['uid']  = 1;  $order_rs = $this->_orderModel->create_order($data);  //庫存減少  $gid = $goodsInfo['id'];  $sql = 'UPDATE goods SET counts = counts - 1 WHERE id = '.$gid;  $result = $this->_goodsModel->exect($sql);  $this->_error = '購買成功';  return true; } /*  * 基於mysql事務驗證庫存資訊  * @desc 事務 和 行鎖 模式,高並發下不會導致超賣,但效率會慢點  * @author liubin  * @date 2017-02-10  說明:  如果$sql_forlock不加寫鎖,並發時,$sql_forlock查詢的記錄存都大於0,可以減庫存操作.  如果$sql_forlock加了寫鎖,並發時,$sql_forlock查詢是等待第一次連結釋放後查詢.所以庫存最多就是5 */ protected function order_check_transaction($gid){  $model = $this->_goodsModel;  $pdo = $model->getHandler();  $gid = intval($gid);  try{   $pdo->beginTransaction();//開啟交易處理   /*    * 1:$sql_forlock如果只加事務,不加寫鎖:    * 開啟事務    * 因為沒有加鎖,讀$sql_forlock後,並發時$sql_inventory之前還可以再讀。    * $sql_inventory之後和commit之前才會鎖定    * 出現超賣跟事務的一致性不衝突    *     *    * 2:$sql_forlock如果加了事務,又加讀鎖:    * 開啟事務    * 第一個會話讀$sql_forlock時加讀鎖,並發時,第二個會話也允許獲得$sql_forlock的讀鎖,    * 但是在第一個會話執行去庫存操作時(寫鎖),寫鎖便會等待第二個會話的讀鎖,第二個會話執行寫操作時,寫鎖便會等待第一個會話的讀鎖,    * 出現死結    * 3:$sql_forlock如果加了事務,又加寫鎖:    * 開啟事務    * 第一個會話讀$sql_forlock時加寫鎖,直到commit才會釋放寫鎖,並發查詢不會出現超賣現象。    *   */   $sql_forlock = 'select * from goods where id = '.$gid .' limit 1 for update';   //$sql_forlock = 'select * from goods where id = '.$gid .' limit 1 LOCK IN SHARE MODE';   //$sql_forlock = 'select * from goods where id = '.$gid .' limit 1';   $result = $pdo->query($sql_forlock,PDO::FETCH_ASSOC);   $goodsInfo = $result->fetch();   if($goodsInfo['counts']>0){    //去庫存    $gid = $goodsInfo['id'];    $sql_inventory = 'UPDATE goods SET counts = counts - 1 WHERE id = '.$gid;    $result = $this->_goodsModel->exect($sql_inventory);    if(!$result){     $pdo->rollBack();     $this->_error = '庫存減少失敗';     return false;    }    //創訂單    $data    = [];    $data['id']   = 'null';    $data['order_id'] = $this->_orderModel->buildOrderNo();    $data['goods_id'] = $goodsInfo['id'];    $data['uid']  = 'abc';    $data['addtime'] = time();    $sql = 'insert into orders (id,order_id,goods_id,uid,addtime) values ('.$data['id'].',"'.$data['order_id'].'","'.$data['goods_id'].'","'.$data['uid'].'","'.$data['addtime'].'")';       $result = $pdo->exec($sql);    if(!$result){     $pdo->rollBack();     $this->_error = '訂單建立失敗';     return false;    }    $pdo->commit();//提交    $this->_error = '購買成功';    return true;   }else{    $this->_error = '庫存不足';    return false;   }  }catch(PDOException $e){   echo $e->getMessage();   $pdo->rollBack();  } } /*  * 建立訂單  * mysql 事物處理,也可以用預存程序  * */ private function create_order($goodsInfo){  //產生訂單  $data    = [];  $data['order_id'] = $this->_orderModel->buildOrderNo();  $data['goods_id'] = $goodsInfo['id'];  $data['addtime'] = time();  $data['uid']  = 1;  $order_rs = $this->_orderModel->create_order($data);  //庫存減少  $gid = $goodsInfo['id'];  $sql = 'UPDATE goods SET counts = counts - 1 WHERE id = '.$gid;  $result = $this->_goodsModel->exect($sql);  return true; }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.