MYSQL商城简单场景处理并发,防止库存超卖

适用于简单商城并发场景,无需借助redis即可实现并发秒杀

// 开启事务
Db::startTrans();
try {
    // 随机购买数量
    $buyNumber = rand(2, 9); 
    // 先减少库存
    Db::table('easycms_goods')->where('id', 1)->setDec('stock', $buyNumber);
    // 查询是否超卖
    $goods = Db::table('easycms_goods')->where('id', 1)->find();
    if($goods['stock'] < 0){
       throw new \think\Exception('库存不足!');
    }
    // 秒杀成功处理
    // ...
  
    // 提交事务
    Db::commit();
} catch (\Exception $e) {
    // 秒杀失败处理
    // ...

    // 回滚事务
    Db::rollback();
}

PS: 大型高并发场景慎用,推荐使用redis列队处理

posted @ 2021-07-04 14:23  黎明1996  阅读(126)  评论(0编辑  收藏  举报