<?php/** * $productTotal 商品總數 * $productSellNum 已售商品數量 * $currentBuyNum 當前購買數量 *///商品總數$productTotal = 100; //當前購買數量$currentBuyNum = 5; try { $redis = ...
<?php
/**
* $productTotal 商品總數
* $productSellNum 已售商品數量
* $currentBuyNum 當前購買數量
*/
//商品總數
$productTotal = 100;
//當前購買數量
$currentBuyNum = 5;
try {
$redis = new redis();
$result = $redis->connect('127.0.0.1',6379);
if(!$result){
throw new Exception('redis連接失敗');
}
} catch (Exception $e){
echo $e->getMessage();
die;
}
//監視 product_sell_num
$redis->watch('product_sell_num');
//已售商品數量
$productSellNum = $redis->get('product_sell_num');
//判斷商品是否剩餘
if($productSellNum + $currentBuyNum <= $productTotal){
$redis->multi();
$redis->set('product_sell_num',$productSellNum + $currentBuyNum);
$status = $redis->exec();
if($status){
//對購買信息處理
}else{
return "搶購失敗";
}
}else{
return "搶購結束";
}