首先开启redis及其配置
php 代码
public function requestAccess($uid,$time=1,$limit=3){
//获取访问用户的IP
$ip=md5(request()->ip($uid));
//获取访问的接口路径
$path=request()->path();
//将IP和访问的接口路径md5加密成一个字符串,这样子就代表同一个客户访问的接口。
$UV=md5($ip.$path);
//每个IP和接口每分钟不能超过的次数
$cacheIp=Cache::get($UV)?:0;
if($cacheIp){
if($cacheIp>$limit){
return false;
}else{
Cache::inc($UV,1);
}
}else{
Cache::set($UV,1,60);
}
//将每个请求的IP地址、参数和路径拼接成同一个用户的一个完全相同的接口。
$post=json_encode(request()->post());
$name=md5($path.$post);
//每个相同的数据多少时间内不能请求
$cache=Cache::get($name);
if($cache==$ip){
return false;
}else{
Cache::set($name,$ip,$time);
return true;
}
}
调用
$user_id= Session::get('user_id');
if (!$this->requestAccess($user_id)){
return json(['code'=>200,'msg'=>'接口调用过于频繁'])->send();
}