效果
1.开启Redis
打开你的Redis软件没有的话可以在小皮环境 软件管理中安装
2 .tp5配置config.php
'cache' => [
// 驱动方式
'type' => 'redis',
// 默认使用的缓存
'default' => [
// 驱动方式
'type' => 'redis',
// 缓存保存目录
'path' => CACHE_PATH,
],
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// redis缓存
'redis' => [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
],
],
3.php代码
function requestAccess($time=1,$limit=3){
//获取访问用户的IP
$ip=md5(request()->ip());
//获取访问的接口路径
$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;
}
}
4. 调用
在你需要限制频次的接口调用
if (!$this->requestAccess()){
echo json(['code'=>200,'msg'=>'接口调用过于频繁'])->send();die;
}