分享按钮

php结合Redis接口访问频率限制

默认分类 / 3119人浏览 / 0人评论

结合封装的 redis 使用代码如下

/**

*
* 限流操作
*
* */
public function frequency(){
   $uid = 1;
   $result = $this->api_frequency_visits($uid);
   if (!$result) {
       echo  json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]]).PHP_EOL;
   }else{
       echo  json_encode(['code'=>1, 'msg'=>'', 'data'=>[
               'uid'=>$uid,
               'other'=>rand()
           ]]).PHP_EOL;
   }

}
 /**
  * @param $uid
  * @return bool|int
  * 检测用户接口访问频率
  */
 function api_frequency_visits ($uid) {
     $key = "user_{$uid}_api_frequency";
     $data =$this->redis->HashGet($key,'',2);
     //需要删除的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;
             //存在需要删除的key
             $this->redis->HashDel($key,$time);
         } else {
             $total += $count;
         }
     }
     //存在需要删除的key
    /* if ($del_key) {
         $this->redis->HashDel($key,$del_key);
     }*/
     if ($total >= $max_frequency) {
         return false;
     }
     return $this->redis->HashInc($key, $now_time, 1);
 }

不结合封装Redis方法单独使用

/** * @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;


 某一个场景 某一个API会去请求MySQL,这个mysql主要是写操作但是我们mysql qps 写只能抗500 限流策略(PHP + redis) 500内的请求 之外的不请求给出提示,如请稍后重试之类

$redis = new \Redis();

$key = "redis_limit_".time();

$get = $redis->inc($key);

if($get <= 500){

//放行 执行代码逻辑

return $get;

}else{

return 0;

}




感谢博主,喝杯咖啡~