创建时间:2022-08-24
运用了 Cache 文件缓存类
引入
use think\facade\Cache;
定义
/**
* 限制某ip一定时间内请求次数(防恶意请求接口)
* 正常请求返回true,超过请求次数的时间返回false
* @param int $num 超过3次不让访问(这里没写错,就是超过3次,不是2次)
* @param int $time 禁止访问后,距离允许下次请求的间隔时间(单位:秒,这里默认是3秒内不允许再次请求)
* @return bool
*/
protected function getResult($num = 2, $time = 3){
$ip = request()->ip(); //获取来源ip
$path = request()->url(); //获取当前地址
$url = $ip . $path; //拿ip和地址拼接成key
// Cache::delete($url);
$res = Cache::get($url); //获取value
if ($res) { //如果有value(说明之前已经请求过了)
if ($res > $num) { //超过规定请求的次数
return false;
}
Cache::inc($url, 1); //没超过规定请求的次数,次数自增1
return true;
} else {
Cache::set($url, 1, $time); //初次请求,写入缓存与有效时间
return true;
}
}使用
$res = $this->getResult(1,3);
if (empty($res)) {
$this->info['code']=201;
$this->info['msg']='请求太快,请3秒之后再试';
return json($this->info);
}
//这里写正常放行的业务代码
$this->info['code']=200;
$this->info['msg']='操作成功';
return json($this->info);