php中使用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 "抢购结束";}

相关推荐