mysql处理高并发,防止库存超卖

来源:互联网 发布:jdk 8u60 linux x32 编辑:程序博客网 时间:2024/05/22 14:14
1、事务处理
   一般情况,事务处理都可以解决

2、每减少库存对应一个订单流水号(这个订单流水号在生成减少库存这个用户动作时就要生成),订单流水号是存在自增ID的表里的,然后统计这个流水,就好解决了。

  例如:总库存:4个商品
            请求人:a,1个商品;b,2个商品;c:3个商品
      
方法一、 beginTranse(开启事务)
  try{
      //quantity 为请求减掉的库存数量
     $dbca->query('update s_store set amount = amount-quanity where postID=12345');
     $result = $dbca->query('select amount from s_store where postID =12345');
        if(result->amount <0){
            throw new Exception('库存不足');
     }
   }catch($e Exception){
      rollBack(回滚)
  }
commit(提交事务)
方法二、beginTranse(开启事务)
        try{
         //quantity 为请求减掉的库存数量
          $dbca->query('update s_store set amount = amount-quanity where amount>=quanity and postID = 12345');
     }catch($e Exception){
      rollBack(回滚)
    }
    commit(提交事务)

个人主页

0 0
原创粉丝点击