首页 > 编程知识 正文

php利用redis踢出,redis的数据队列

时间:2023-05-04 08:03:16 阅读:143934 作者:1146

百度自己写了几天的班。 其中包括锁定、解锁和入队操作。 还没有写异步库存削减、出队列等操作。 写完之后再编辑

用apache的ab测试-n 500 -c 100进行测试,结果没有出现超卖品

这个代码在项目中没有用过,所以觉得哪里有问题的人请指出来。 我们一起讨论改进这个代码

? phpclassredislock { function _ _ construct ({ $ r=new (redis ) ); $r-pconnect () 127.0.0.1 )、) 6379 ); $this-redis=$r; $this-timeout=3; $ this-good _ stock _ queue=' good _ stock _ queue _ '; $ this-joined _ queue=' joined _ queue _ '; $this-uid_queue='uid_queue '; }functionget_set_by_name($name,$type=' ' ) {$rs=$this-redis; if($type=='zset ' ) return $ RS-z范围) $name,0,-1); }返回$ RS-get ($ name ); //库存队列function init _ goodstock _ queue ($ num,$gid ) ) {$rs=$this-redis; $ RS-del ($ this-good _ stock _ queue.$ GID ); for($I=0; $i $num; $I({$RS-Lpush ) $this-good_stock_queue.$GID,1 ); } $ result=$ RS-llen ($ this-good _ stock _ queue.$ GID ); if($result ) {返回真; }返回假; //锁定操作functionadd_lock($key,$timeout=null,$waitsec=100000 ) {$rr=$this-redis; $ lock _ name=$ this-get _ lock _ name $ key; $timeout=$timeout? $timeout : $this-timeout; $time=time (; $expire_time=$time $timeout; $get_lock=$RR-setNX($lock_name,$expire_time ); if $ get _ lock (返回$ expire _ time; }while(1) usleep ) $Waitsec; $ old _ expire _ time=$ RR-get $ lock _ name; //如果锁定尚未过期,则返回if($old_expire_time=time ) ) {continue; }$new_expire_time=time () $timeout; $ last _ expire _ time=$ RR-getset ($ lock _ name,$new_expire_time ); //继续获取,如果与上一个锁定的score不匹配,则if($last_expire_time!=$old_expire_time ) {continue; }$get_lock=$new_expire_time; 布雷克; }return $get_lock; //dump($RR-get ) ' ok ' ); (//functionrelease_lock ) $key,$score ) {$rr=$this-redis; $ lock _ name=$ this-get _ lock _ name $ key; if($scoretime ) ) if ) $RR-del ) $lock_name ) {return true; } }返回假; //锁定名称functionget_lock_name($key ) {return 'lock_'.$key; //functionenqueue($uid,$gid ) ) {$rr=$this-redis; //确定已加入的队列中是否还有$ is _ joined=$ RR-get ($ this-joined _ queue.$ GID,$uid )//dump ($ is if (! $is_joined ) {//确定库存队列$ stock _ num=$ RR-llen ($ this-good _ stock _ queue.$ GID ); //dump($stock_num; (if ) $stock_num ) ) /入队) $time_score=time ); $ uid _ queue _ len=$ RR-z card ($ this-uid _ queue ); //此处为测试秒杀if($uid_queue_len10 ) ) $se=$RR-zadd ) $this-uid_queue,$time_score,$uid ); (//$RR-lpop ) $this-good_stock_queue.$GID ); 返回真; } }返回假; 离开function dequeue () )队

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。