zoukankan      html  css  js  c++  java
  • PHP实现高并发下的秒杀功能–Laravel

    namespace AppHttpControllersSecKill;


    use AppHttpControllersController;
    use Exception;
    use IlluminateSupportFacadesDB;
    use IlluminateSupportFacadesRedis;

    class SecKillController extends Controller
    {

    /**
    * 往redis的隊列中添加庫存(用於測試的數據)
    *
    */
    public function setAddRedis(){
    $store=150;
    $res=Redis::llen('goods_store');
    echo $res;
    $count=$store-$res;
    for($i=0;$i<$count;$i++){
    Redis::lpush('goods_store',1);
    }
    echo Redis::llen('goods_store');
    }

    //生成唯一订单号
    public function build_order_no(){
    return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
    * 使用redis队列,因为pop操作是原子的,即使有很多用户同时到达,也是依次执行,推荐使用(mysql事务在高并发下性能下降很厉害,文件锁的方式也是)
    * @param $goods_id
    * @return string
    */
    public function getGood($goods_id){
    $price =10;
    $count = Redis::lpop("goods_store");
    if(!$count){
    return "error:no store redis";
    }
    $order_sn=$this->build_order_no();

    DB::insert('insert into ih_order (order_sn,user_id,goods_id,price) values (?, ?,?,?)', [$order_sn, rand(1,15),$goods_id,$price]);

    $res = DB::update('update in_store set store_number = store_number-1 where goods_id = ?', [$goods_id]);
    if($res){
    return "库存减少成功";
    } else{
    return "库存减少失敗";
    }
    }

    public function doLog($log){
    file_put_contents("test.txt",$log.' ',FILE_APPEND);
    }

    /**
    *
    * desc 在事务中对数据进行加锁,当事务进行提交(commit)或者回滚(rollBack)时都会取消锁。
    * 单纯的开启一个事务,并不会对事务中的数据进行加锁,只会保证数据的完整性.其他数据是否可以访问,不能保证数据库的数据单一操作
    * @param $goods_id
    * @return bool
    */
    public function getGoodByMysql($goods_id){
    // 开启事务
    DB::beginTransaction();
    try {
    // 需要处理的逻辑 doSomething;
    $res = DB::table("in_store")->where(['goods_id'=>$goods_id])->sharedLock()->first();
    //对事务中数据进行加锁(悲观锁)
    if($res->store_number) {
    $store_number = $res->store_number-1;
    $num = DB::table('in_store')->where('goods_id',$goods_id)->decrement('store_number');
    if($num) {
    // 提交事务
    DB::commit();
    $msg = "减少库存成功";
    } else {
    $msg = "减少库存失败";
    }
    } else {
    $msg ="库存不够";
    }
    DB::rollBack();
    return $msg;
    } catch (Exception $e) {
    // 数据回滚, 当try中的语句抛出异常。
    DB::rollBack();
    return false;
    // 执行一些提醒操作等等...
    }

    }

    }

  • 相关阅读:
    逍遥刘强 - 期货大作手风云录(2015年8月28日)
    雷米 - 心理罪:画像(2015年8月17日)
    雷米 - 心理罪:城市之光(2015年8月11日)
    雷米 - 心理罪:暗河(2015年8月9日)
    雷米 - 心理罪:教化场(2015年8月8日)
    付海棠 - 一个农民的亿万传奇(2015年7月14日)
    阿西莫夫 - 神们自己(2015年6月23日)
    张维为 - 中国震撼:一个”文明型国家“的崛起(2015年5月30日)
    华彬 - 华彬讲透孙子兵法(2015年5月22日)
    股峰求道 - 炼股成金:从散户到操盘手的修炼法则(2015年5月11日)
  • 原文地址:https://www.cnblogs.com/vinzen/p/9804276.html
Copyright © 2011-2022 走看看