[PHP] PHP redis滑动窗口频率限制
2023-02-18 15:37:07 时间
使用redis进行频率限制 , 并且使用滑动窗口形式 , 可以防止临界点时的超频
代码在下面 ,请自行替换new Redis()对象
function check($queueName,$count,$timeWindow){ $currTime=time(); $redis = php-redis对象;//自行连接redis $length=$redis->lLen($queueName); if($length<$count){ $redis->lPush($queueName,$currTime); $redis->expire($queueName,$timeWindow); return true; } //队列满了,取出最早访问的时间 $earlyTime= $redis->lIndex($queueName,$length-1); //说明最早期的时间还在时间窗口内,还没过期,所以不允许通过 if ($currTime-$earlyTime <= $timeWindow) { return false; } else { //说明最早期的访问应该过期了,去掉最早期的 $redis->rPop($queueName); $redis->lPush($queueName,$currTime); $redis->expire($queueName,$timeWindow); } return true; }
使用方式 , 比如说24小时一次 ,对手机号的限制
if(check("tel-{$telephone}:",1,24*3600)){ $json=array("code"=>400,"msg"=>"当前手机号频率限制"); exit(json_encode($json)); }
相关文章
- Redis分布式锁的10个坑
- 如何解决 Redis 数据倾斜、热点等问题
- 免费给自己的网站加 HTTPS
- iterm2 快捷键(转载)
- Too many authentication failures for xxxx_username
- peewee insert 数据时报错:'buffer' object has no attribute 'translate'
- virtualenv 虚拟环境报错:setuptools pip wheel failed with error code 1
- supervisor 安装、配置、常用命令
- _ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
- [MySQL]支持 emoji(字符集问题)
- [MySQL]长连接和短链接(转载)
- 解决 InsecurePlatformWarning: A true SSLContext object is not available.
- Mac总是自动启动脚本
- Max retries exceeded with url
- brew tap homebrew-science fails
- 持续集成是什么?(转载)
- [编辑器]vim常用操作
- Mac下中文输入法突然没了选字框
- install dm.xmlsec.binding 失败
- [MySQL]创建数据库以及设置编码