PHP+redis實(shí)現(xiàn)的限制搶購(gòu)防止商品超發(fā)功能詳解
本文實(shí)例講述了PHP+redis實(shí)現(xiàn)的限制搶購(gòu)防止商品超發(fā)功能。分享給大家供大家參考,具體如下:
- redis不僅僅是單純的緩存,它還有一些特殊的功能,在一些特殊場(chǎng)景上很好用。redis中key的原子自增incrby和判斷key不存在再寫(xiě)入的setnx方法,可以有效的防止超發(fā)。
- 下面使用兩個(gè)不同的方式來(lái)說(shuō)明利用redis做商品購(gòu)買(mǎi)庫(kù)存數(shù)量限制。
- 業(yè)務(wù)場(chǎng)景很簡(jiǎn)單,就是限制搶購(gòu)5個(gè)商品,模擬并發(fā)請(qǐng)求搶購(gòu)商品,每搶購(gòu)一次對(duì)應(yīng)redis中的key值增加一次,通過(guò)判斷限購(gòu)的數(shù)量來(lái)限制搶購(gòu),搶購(gòu)成功寫(xiě)入成功日志,失敗寫(xiě)入失敗的信息記錄,通過(guò)記錄的數(shù)量來(lái)判斷是否超發(fā)。
文件index.php
<?php require_once './myRedis.php'; require_once './function.php'; class sendAward{ public $conf = []; const V1 = 'way1';//版本一 const V2 = 'way2';//版本二 const AMOUNTLIMIT = 5;//搶購(gòu)數(shù)量限制 const INCRAMOUNT = 1;//redis遞增數(shù)量值 //初始化調(diào)用對(duì)應(yīng)方法執(zhí)行商品發(fā)放 public function __construct($conf,$type){ $this->conf = $conf; if(empty($type)) return ''; if($type==self::V1){ $this->way1(self::V1); }elseif($type==self::V2){ $this->way2(self::V2); }else{ return ''; } } //搶購(gòu)商品方式一 protected function way1($v){ $redis = new myRedis($this->conf); $keyNmae = getKeyName($v); if(!$redis->exists($keyNmae)){ $redis->set($keyNmae,0); } $currAmount = $redis->get($keyNmae); if(($currAmount+self::INCRAMOUNT)>self::AMOUNTLIMIT){ writeLog("沒(méi)有搶到商品",$v); return; } $redis->incrby($keyNmae,self::INCRAMOUNT); writeLog("搶到商品",$v); } //搶購(gòu)商品方式二 protected function way2($v){ $redis = new myRedis($this->conf); $keyNmae = getKeyName($v); if(!$redis->exists($keyNmae)){ $redis->setnx($keyNmae,0); } if($redis->incrby($keyNmae,self::INCRAMOUNT) > self::AMOUNTLIMIT){ writeLog("沒(méi)有搶到商品",$v); return; } writeLog("搶到商品",$v); } } //實(shí)例化調(diào)用對(duì)應(yīng)執(zhí)行方法 $type = isset($_GET['v'])?$_GET['v']:'way1'; $conf = [ 'host'=>'192.168.0.214','port'=>'6379', 'auth'=>'test','db'=>2, ]; new sendAward($conf,$type);
文件myRedis.php
<?php /** * @desc 自定義redis操作類(lèi) * **/ class myRedis{ public $handler = NULL; public function __construct($conf){ $this->handler = new Redis(); $this->handler->connect($conf['host'], $conf['port']); //連接Redis //設(shè)置密碼 if(isset($conf['auth'])){ $this->handler->auth($conf['auth']); //密碼驗(yàn)證 } //選擇數(shù)據(jù)庫(kù) if(isset($conf['db'])){ $this->handler->select($conf['db']);//選擇數(shù)據(jù)庫(kù)2 }else{ $this->handler->select(0);//默認(rèn)選擇0庫(kù) } } //獲取key的值 public function get($name){ return $this->handler->get($name); } //設(shè)置key的值 public function set($name,$value){ return $this->handler->set($name,$value); } //判斷key是否存在 public function exists($key){ if($this->handler->exists($key)){ return true; } return false; } //當(dāng)key不存在的設(shè)置key的值,存在則不設(shè)置 public function setnx($key,$value){ return $this->handler->setnx($key,$value); } //將key的數(shù)值增加指定數(shù)值 public function incrby($key,$value){ return $this->handler->incrBy($key,$value); } }
文件function.php
<?php //獲取商品key名稱(chēng) function getKeyName($v) { return "send_goods_".$v; } //日志寫(xiě)入方法 function writeLog($msg,$v) { $log = $msg.PHP_EOL; file_put_contents("log/$v.log",$log,FILE_APPEND); }
1.ab工具并發(fā)測(cè)試way1方法
[root@localhost oversend]# ab -c 100 -n 200 http://192.168.0.213:8083/index.php?v=way1 This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 192.168.0.213 (be patient) Completed 100 requests Completed 200 requests Finished 200 requests Server Software: nginx Server Hostname: 192.168.0.213 Server Port: 8083 Document Path: /index.php?v=way1 Document Length: 0 bytes Concurrency Level: 100 Time taken for tests: 0.089 seconds Complete requests: 200 Failed requests: 0 Write errors: 0 Total transferred: 30600 bytes HTML transferred: 0 bytes Requests per second: 2243.13 [#/sec] (mean) Time per request: 44.581 [ms] (mean) Time per request: 0.446 [ms] (mean, across all concurrent requests) Transfer rate: 335.16 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 6 2.2 5 17 Processing: 2 28 16.3 25 55 Waiting: 1 26 15.2 24 50 Total: 5 34 16.3 30 60 Percentage of the requests served within a certain time (ms) 50% 30 66% 35 75% 54 80% 56 90% 57 95% 60 98% 60 99% 60 100% 60 (longest request)
v1方法日志分析
[root@localhost log]# less -N way1.log 1 搶到商品 2 搶到商品 3 搶到商品 4 搶到商品 5 搶到商品 6 搶到商品 7 沒(méi)有搶到商品 8 沒(méi)有搶到商品 9 沒(méi)有搶到商品 10 沒(méi)有搶到商品 11 沒(méi)有搶到商品 12 沒(méi)有搶到商品
觀察日志發(fā)現(xiàn) 搶到商品的記錄有6條超過(guò)正常的5條,說(shuō)明超發(fā)了
2.ab工具并發(fā)測(cè)試way2方法
[root@localhost oversend]# ab -c 100 -n 200 http://192.168.0.213:8083/index.php?v=way2 This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 192.168.0.213 (be patient) Completed 100 requests Completed 200 requests Finished 200 requests Server Software: nginx Server Hostname: 192.168.0.213 Server Port: 8083 Document Path: /index.php?v=way2 Document Length: 0 bytes Concurrency Level: 100 Time taken for tests: 0.087 seconds Complete requests: 200 Failed requests: 0 Write errors: 0 Total transferred: 31059 bytes HTML transferred: 0 bytes Requests per second: 2311.68 [#/sec] (mean) Time per request: 43.259 [ms] (mean) Time per request: 0.433 [ms] (mean, across all concurrent requests) Transfer rate: 350.58 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 6 5.4 5 13 Processing: 3 31 16.6 30 70 Waiting: 1 30 16.6 30 70 Total: 5 37 18.5 32 82 Percentage of the requests served within a certain time (ms) 50% 32 66% 41 75% 45 80% 50 90% 68 95% 80 98% 81 99% 82 100% 82 (longest request)
v2方法日志分析
[root@localhost log]# less -N v2.log [root@localhost log]# less -N way2.log 1 搶到商品 2 搶到商品 3 搶到商品 4 搶到商品 5 沒(méi)有搶到商品 6 搶到商品 7 沒(méi)有搶到商品 8 沒(méi)有搶到商品 9 沒(méi)有搶到商品 10 沒(méi)有搶到商品
總結(jié):觀察日志可知搶到商品的日志記錄是5條并沒(méi)有超發(fā),說(shuō)明利用這種方式可以限制住庫(kù)存的數(shù)量。之所以超發(fā)是因?yàn)榉椒ㄒ恢型ㄟ^(guò)加法來(lái)判斷限制條件的同時(shí),并發(fā)一大,就會(huì)越過(guò)這個(gè)判斷條件出現(xiàn)會(huì)超發(fā),redis的在這方面就體現(xiàn)優(yōu)勢(shì)了。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php+redis數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
php編程實(shí)現(xiàn)獲取excel文檔內(nèi)容的代碼實(shí)例
最近剛剛做了個(gè)導(dǎo)入excle文件,群發(fā)短信的功能,在這里總結(jié)下用php獲取excle文件數(shù)據(jù)的方法2011-06-06PHP實(shí)現(xiàn)的超長(zhǎng)文本分頁(yè)顯示功能示例
這篇文章主要介紹了PHP實(shí)現(xiàn)的超長(zhǎng)文本分頁(yè)顯示功能,涉及php針對(duì)字符串的計(jì)算、截取、遍歷等相關(guān)操作技巧,可實(shí)現(xiàn)針對(duì)超長(zhǎng)文本的分頁(yè)顯示功能,需要的朋友可以參考下2018-06-06php采用ajax數(shù)據(jù)提交post與post常見(jiàn)方法總結(jié)
這篇文章主要介紹了php采用ajax數(shù)據(jù)提交post與post常見(jiàn)方法,實(shí)例總結(jié)了json格式傳遞數(shù)據(jù)的優(yōu)點(diǎn)并總結(jié)了四種常見(jiàn)的POST提交數(shù)據(jù)方式,需要的朋友可以參考下2014-11-11PHP輸出圖像imagegif、imagejpeg與imagepng函數(shù)用法分析
這篇文章主要介紹了PHP輸出圖像imagegif、imagejpeg與imagepng函數(shù)用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了imagegif()、imagejpeg()、imagepng()和imagewbmp()函數(shù)的功能、參數(shù)含義及使用技巧,需要的朋友可以參考下2016-11-11簡(jiǎn)單了解將WordPress中的工具欄移到底部的小技巧
這篇文章主要介紹了將WordPress中的工具欄移到底部的小技巧,隨著新版的Chrome和WordPress的發(fā)布,文中最后提到的顯示問(wèn)題也應(yīng)當(dāng)能夠得到解決,需要的朋友可以參考下2015-12-12php數(shù)組函數(shù)序列之a(chǎn)rray_key_exists() - 查找數(shù)組鍵名是否存在
array_key_exists() 函數(shù)判斷某個(gè)數(shù)組中是否存在指定的 key,如果該 key 存在,則返回 true,否則返回 false2011-10-10