PHP+redis实现的限制抢购防止商品超发功能详解
本文实例讲述了PHP+redis实现的限制抢购防止商品超发功能。分享给大家供大家参考,具体如下:
- redis不仅仅是单纯的缓存,它还有一些特殊的功能,在一些特殊场景上很好用。redis中key的原子自增incrby和判断key不存在再写入的setnx方法,可以有效的防止超发。
- 下面使用两个不同的方式来说明利用redis做商品购买库存数量限制。
- 业务场景很简单,就是限制抢购5个商品,模拟并发请求抢购商品,每抢购一次对应redis中的key值增加一次,通过判断限购的数量来限制抢购,抢购成功写入成功日志,失败写入失败的信息记录,通过记录的数量来判断是否超发。
文件index.php
conf=$conf;
if(empty($type))
return'';
if($type==self::V1){
$this->way1(self::V1);
}elseif($type==self::V2){
$this->way2(self::V2);
}else{
return'';
}
}
//抢购商品方式一
protectedfunctionway1($v){
$redis=newmyRedis($this->conf);
$keyNmae=getKeyName($v);
if(!$redis->exists($keyNmae)){
$redis->set($keyNmae,0);
}
$currAmount=$redis->get($keyNmae);
if(($currAmount+self::INCRAMOUNT)>self::AMOUNTLIMIT){
writeLog("没有抢到商品",$v);
return;
}
$redis->incrby($keyNmae,self::INCRAMOUNT);
writeLog("抢到商品",$v);
}
//抢购商品方式二
protectedfunctionway2($v){
$redis=newmyRedis($this->conf);
$keyNmae=getKeyName($v);
if(!$redis->exists($keyNmae)){
$redis->setnx($keyNmae,0);
}
if($redis->incrby($keyNmae,self::INCRAMOUNT)>self::AMOUNTLIMIT){
writeLog("没有抢到商品",$v);
return;
}
writeLog("抢到商品",$v);
}
}
//实例化调用对应执行方法
$type=isset($_GET['v'])?$_GET['v']:'way1';
$conf=[
'host'=>'192.168.0.214','port'=>'6379',
'auth'=>'test','db'=>2,
];
newsendAward($conf,$type);
文件myRedis.php
handler=newRedis();
$this->handler->connect($conf['host'],$conf['port']);//连接Redis
//设置密码
if(isset($conf['auth'])){
$this->handler->auth($conf['auth']);//密码验证
}
//选择数据库
if(isset($conf['db'])){
$this->handler->select($conf['db']);//选择数据库2
}else{
$this->handler->select(0);//默认选择0库
}
}
//获取key的值
publicfunctionget($name){
return$this->handler->get($name);
}
//设置key的值
publicfunctionset($name,$value){
return$this->handler->set($name,$value);
}
//判断key是否存在
publicfunctionexists($key){
if($this->handler->exists($key)){
returntrue;
}
returnfalse;
}
//当key不存在的设置key的值,存在则不设置
publicfunctionsetnx($key,$value){
return$this->handler->setnx($key,$value);
}
//将key的数值增加指定数值
publicfunctionincrby($key,$value){
return$this->handler->incrBy($key,$value);
}
}
文件function.php
1.ab工具并发测试way1方法
[root@localhostoversend]#ab-c100-n200http://192.168.0.213:8083/index.php?v=way1 ThisisApacheBench,Version2.3<$Revision:655654$> Copyright1996AdamTwiss,ZeusTechnologyLtd,http://www.zeustech.net/ LicensedtoTheApacheSoftwareFoundation,http://www.apache.org/ Benchmarking192.168.0.213(bepatient) Completed100requests Completed200requests Finished200requests ServerSoftware:nginx ServerHostname:192.168.0.213 ServerPort:8083 DocumentPath:/index.php?v=way1 DocumentLength:0bytes ConcurrencyLevel:100 Timetakenfortests:0.089seconds Completerequests:200 Failedrequests:0 Writeerrors:0 Totaltransferred:30600bytes HTMLtransferred:0bytes Requestspersecond:2243.13[#/sec](mean) Timeperrequest:44.581[ms](mean) Timeperrequest:0.446[ms](mean,acrossallconcurrentrequests) Transferrate:335.16[Kbytes/sec]received ConnectionTimes(ms) minmean[+/-sd]medianmax Connect:062.2517 Processing:22816.32555 Waiting:12615.22450 Total:53416.33060 Percentageoftherequestsservedwithinacertaintime(ms) 50%30 66%35 75%54 80%56 90%57 95%60 98%60 99%60 100%60(longestrequest)v1方法日志分析
[root@localhostlog]#less-Nway1.log 1抢到商品 2抢到商品 3抢到商品 4抢到商品 5抢到商品 6抢到商品 7没有抢到商品 8没有抢到商品 9没有抢到商品 10没有抢到商品 11没有抢到商品 12没有抢到商品观察日志发现抢到商品的记录有6条超过正常的5条,说明超发了
2.ab工具并发测试way2方法
[root@localhostoversend]#ab-c100-n200http://192.168.0.213:8083/index.php?v=way2 ThisisApacheBench,Version2.3<$Revision:655654$> Copyright1996AdamTwiss,ZeusTechnologyLtd,http://www.zeustech.net/ LicensedtoTheApacheSoftwareFoundation,http://www.apache.org/ Benchmarking192.168.0.213(bepatient) Completed100requests Completed200requests Finished200requests ServerSoftware:nginx ServerHostname:192.168.0.213 ServerPort:8083 DocumentPath:/index.php?v=way2 DocumentLength:0bytes ConcurrencyLevel:100 Timetakenfortests:0.087seconds Completerequests:200 Failedrequests:0 Writeerrors:0 Totaltransferred:31059bytes HTMLtransferred:0bytes Requestspersecond:2311.68[#/sec](mean) Timeperrequest:43.259[ms](mean) Timeperrequest:0.433[ms](mean,acrossallconcurrentrequests) Transferrate:350.58[Kbytes/sec]received ConnectionTimes(ms) minmean[+/-sd]medianmax Connect:065.4513 Processing:33116.63070 Waiting:13016.63070 Total:53718.53282 Percentageoftherequestsservedwithinacertaintime(ms) 50%32 66%41 75%45 80%50 90%68 95%80 98%81 99%82 100%82(longestrequest)v2方法日志分析
[root@localhostlog]#less-Nv2.log [root@localhostlog]#less-Nway2.log 1抢到商品 2抢到商品 3抢到商品 4抢到商品 5没有抢到商品 6抢到商品 7没有抢到商品 8没有抢到商品 9没有抢到商品 10没有抢到商品总结:观察日志可知抢到商品的日志记录是5条并没有超发,说明利用这种方式可以限制住库存的数量。之所以超发是因为方法一中通过加法来判断限制条件的同时,并发一大,就会越过这个判断条件出现会超发,redis的在这方面就体现优势了。
完整代码github地址
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+redis数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。