redis 秒杀多并发处理

网上有很多处理并发的例子 但是感觉太麻烦啦 所以凭着自己的感觉写了一个 
测试 1秒 300个请求 是通过的 
欢迎各位大神指点
学习参考 
http://doc.redisfans.com/topic/transaction.html#check-and-set
// 1乐观锁
public function optimisticlock($key){
    if(!$this->_redis->EXISTS($key)){

        return false;
    }
    $this->_redis->WATCH($key); //监听事务
    // 库存数量
    $value =  $this->_redis->get($key);
    if(!$value){

        return false;
    }
    $value = $value - 1;
    $this->_redis->MULTI;  //事务开始
     $resoult=$this->_redis->set($key,$value);
    $this->_redis->EXEC;  //事务结束
    
    return $resoult;
}

测试过程
huiting@USER-WangHuiTing:/opt$ http_load -p 300 -s 1 test.txt 
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
http://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong
18764 fetches, 300 max parallel, 3.4125e+06 bytes, in 1.00005 seconds
181.864 mean bytes/connection
18763.1 fetches/sec, 3.41234e+06 bytes/sec
msecs/connect: 0.206676 mean, 2.604 max, 0.032 min
msecs/first-response: 4.53481 mean, 981.273 max, 0.188 min
15 bad byte counts
HTTP response codes:
  code 200 -- 15
  code 502 -- 18749

第二种方式用列表的方式 list 利用redis 的原子性 lpop 单进程 一个一个排队释放队列里面的元素
1,入库存
// 商品库存存redis
public function set_stock($stock,$goods_id){

    $key = 'seckill'.'_'.$goods_id;

    for ($i=0;$i<$stock;$i++){

        $this->_redis->lpush($key,1);
    }

}
2,出库存
//秒杀出库存
public function out_stock($goods_id){

    $key = 'seckill'.'_'.$goods_id;
    $count = $this->_redis->lpop($key);
    if(!$count){
        //debug_log_write();
        return false;
    }

    return true;
}




猜你喜欢

转载自blog.csdn.net/u013303689/article/details/78792791