发现网上很多限制都只是1分钟(或者某个时间)内访问的限制
比如1分钟限制10次 那我在59秒的访问了10次,然后key 又过期了,接下来1分钟又可以访问了 。这种限制根本就不合理
所以有了我的想法
直接上代码吧
- /**
- * @param $uid
- * @return bool|int
- * 检测用户接口访问频率
- */
- function api_frequency_visits ($uid) {
- $key = "user:{$uid}:api:frequency";
- $redis = new Redis();
- $redis->connect('127.0.0.1');
- $data = $redis->hGetAll($key);
- //需要删除的key
- $del_key = [];
- //时间内访问的总次数
- $total = 0;
- //时间内最大访问次数
- $max_frequency = 10;
- //当前时间
- $now_time = time();
- //限制时间
- $limit_time = 60;
- foreach ($data as $time=>$count) {
- if ($time < $now_time - $limit_time) {
- $del_key[] = $time;
- } else {
- $total += $count;
- }
- }
- //存在需要删除的key
- if ($del_key) {
- $redis->hDel($key, ...$del_key);
- }
- if ($total >= $max_frequency) {
- return false;
- }
- return $redis->hIncrBy($key, $now_time, 1);
- }
- $uid = 1;
- $result = api_frequency_visits($uid);
- if (!$result) {
- echo json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]]);die;
- }
- echo json_encode(['code'=>1, 'msg'=>'', 'data'=>[
- 'uid'=>$uid,
- 'other'=>rand()
- ]]);die;
限制时间,限制次数这些都可以修改,包括根据用户id也可以换成自己想要的限制,比如IP等
key过期时间也是可以添加的