redis 秒杀多并发处理

来源:互联网 发布:淘宝无线端链接转化 编辑:程序博客网 时间:2024/06/06 00:45
网上有很多处理并发的例子 但是感觉太麻烦啦 所以凭着自己的感觉写了一个 
测试 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 wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wronghttp://www.yuexing.eihoo.cn/index.php?mod=test&act=optimisticlock: byte count wrong18764 fetches, 300 max parallel, 3.4125e+06 bytes, in 1.00005 seconds181.864 mean bytes/connection18763.1 fetches/sec, 3.41234e+06 bytes/secmsecs/connect: 0.206676 mean, 2.604 max, 0.032 minmsecs/first-response: 4.53481 mean, 981.273 max, 0.188 min15 bad byte countsHTTP response codes:  code 200 -- 15  code 502 -- 18749
第二种方式用列表的方式 list 利用redis 的原子性 lpop 单进程 一个一个排队释放队列里面的元素
1,入库存
// 商品库存存redispublic 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;}

原创粉丝点击