實現(xiàn)功能:
- 基于redis隊列,防止高并發(fā)的超賣
- 基于mysql的事務(wù)加排它鎖,防止高并發(fā)的超賣
基于redis隊列工作流程: - 管理員根據(jù)goods表中的庫存,創(chuàng)建redis商品庫存隊列
- 客戶端訪問秒殺API
- web服務(wù)器先從redis的商品庫存隊列中查詢剩余庫存重點內(nèi)容
- redis隊列中有剩余,則在mysql中創(chuàng)建訂單,去庫存,搶購成功
- redis隊列中沒有剩余,則提示庫存不足,搶購失敗重點內(nèi)容
基于mysql事務(wù)和排它鎖工作流程: - 開啟事務(wù)
- 查詢庫存,并顯示的設(shè)置寫鎖(排他鎖):SELECT * FROM goods WHERE id = 1 FOR UPDATE
- 生成訂單
- 去庫存,隱示的設(shè)置寫鎖(排他鎖):UPDATE goods SET counts = counts – 1 WHERE id = 1
- commit,釋放鎖
注意:第二步步可以設(shè)置共享鎖,不然有可能會造成死鎖。
補充:
mysql鎖機制分為表級鎖和行級鎖,本文就和大家分享一下我對mysql中行級鎖中的共享鎖與排他鎖進(jìn)行分享交流。
共享鎖又稱為讀鎖,簡稱S鎖,顧名思義,共享鎖就是多個事務(wù)對于同一數(shù)據(jù)可以共享一把鎖,都能訪問到數(shù)據(jù),但是只能讀不能修改。
排他鎖又稱為寫鎖,簡稱X鎖,顧名思義,排他鎖就是不能與其他所并存,如一個事務(wù)獲取了一個數(shù)據(jù)行的排他鎖,其他事務(wù)就不能再獲取該行的其他鎖,包括共享鎖和排他鎖,但是獲取排他鎖的事務(wù)是可以對數(shù)據(jù)就行讀取和修改。
對于共享鎖很好理解,就是多個事務(wù)只能讀數(shù)據(jù)不能改數(shù)據(jù),對于排他鎖大家的理解可能就有些差別,我當(dāng)初就犯了一個錯誤,以為排他鎖鎖住一行數(shù)據(jù)后,其他事務(wù)就不能讀取和修改該行數(shù)據(jù),其實不是這樣的。排他鎖指的是一個事務(wù)在一行數(shù)據(jù)加上排他鎖后,其他事務(wù)不能再在其上加其他的鎖。mysql InnoDB引擎默認(rèn)的修改數(shù)據(jù)語句,update,delete,insert都會自動給涉及到的數(shù)據(jù)加上排他鎖,select語句默認(rèn)不會加任何鎖類型,如果加排他鎖可以使用select ...for update語句,加共享鎖可以使用select ... lock in share mode語句。所以加過排他鎖的數(shù)據(jù)行在其他事務(wù)種是不能修改數(shù)據(jù)的,也不能通過for update和lock in share mode鎖的方式查詢數(shù)據(jù),但可以直接通過select ...from...查詢數(shù)據(jù),因為普通查詢沒有任何鎖機制。
代碼:
<?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 = '';
/* - 構(gòu)造器
/
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 高并發(fā)下會導(dǎo)致超賣
- @author liubin
- @date 2017-02-10
*/
protected function order_check_mysql($gid){
$model = $this->_goodsModel;
$pdo = $model->getHandler();
$gid = intval($gid);
/*
- 1:$sql_forlock如果不加事務(wù),不加寫鎖:
- 超賣非常嚴(yán)重,就不說了
- 2:$sql_forlock如果不加事務(wù),只加寫鎖:
- 第一個會話讀$sql_forlock時加寫鎖,第一個會話$sql_forlock查詢結(jié)束會釋放該行鎖.
- 第二個會話在第一個會話釋放后讀$sql_forlock的寫鎖時,會再次$sql_forlock查庫存
- 導(dǎo)致超賣現(xiàn)象產(chǎn)生
*/
$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){
//創(chuàng)訂單
$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是底層是單線程的,命令執(zhí)行是原子操作,包括lpush,lpop等.高并發(fā)下不會導(dǎo)致超賣
- @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事務(wù)驗證庫存信息
- @desc 事務(wù) 和 行鎖 模式,高并發(fā)下不會導(dǎo)致超賣,但效率會慢點
- @author liubin
- @date 2017-02-10
說明:
如果$sql_forlock不加寫鎖,并發(fā)時,$sql_forlock查詢的記錄存都大于0,可以減庫存操作.
如果$sql_forlock加了寫鎖,并發(fā)時,$sql_forlock查詢是等待第一次鏈接釋放后查詢.所以庫存最多就是5
*/
protected function order_check_transaction($gid){
$model = $this->_goodsModel;
$pdo = $model->getHandler();
$gid = intval($gid);
try{
$pdo->beginTransaction();//開啟事務(wù)處理
/*
* 1:$sql_forlock如果只加事務(wù),不加寫鎖:
* 開啟事務(wù)
* 因為沒有加鎖,讀$sql_forlock后,并發(fā)時$sql_inventory之前還可以再讀。
* $sql_inventory之后和commit之前才會鎖定
* 出現(xiàn)超賣跟事務(wù)的一致性不沖突
*
*
* 2:$sql_forlock如果加了事務(wù),又加讀鎖:
* 開啟事務(wù)
* 第一個會話讀$sql_forlock時加讀鎖,并發(fā)時,第二個會話也允許獲得$sql_forlock的讀鎖,
* 但是在第一個會話執(zhí)行去庫存操作時(寫鎖),寫鎖便會等待第二個會話的讀鎖,第二個會話執(zhí)行寫操作時,寫鎖便會等待第一個會話的讀鎖,
* 出現(xiàn)死鎖
* 3:$sql_forlock如果加了事務(wù),又加寫鎖:
* 開啟事務(wù)
* 第一個會話讀$sql_forlock時加寫鎖,直到commit才會釋放寫鎖,并發(fā)查詢不會出現(xiàn)超賣現(xiàn)象。
*
*/
$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;
}
//創(chuàng)訂單
$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 = '訂單創(chuàng)建失敗';
return false;
}
$pdo->commit();//提交
$this->_error = '購買成功';
return true;
}else{
$this->_error = '庫存不足';
return false;
}
}catch(PDOException $e){
echo $e->getMessage();
$pdo->rollBack();
}
}
/*
- 創(chuàng)建訂單
- 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;
}
}