一. 在接口中判断访问来源,例如php使用HTTP_REFERER来判断来源,如果是直接访问接口的请求不予处理,如果是从网页调用的请求再做处理。
二 通过redis限制用户一分钟内访问次数
$key = 'user:1:api_count';
$limit = 10;
$check = $redis->exists($key);
if($check){
$redis->incr($key);
$count = $redis->get($key);
if($count >$limit ){
exit('your have too many request');
}
}else{
$redis->incr($key);
$redis->expire($key,60);
}
$count = $redis->get($key);
echo 'You have '.$count.' request';
实现使用中间件进行接口拦截
use think\facade\Cache;
public function handle($request, \Closure $next)
{
$id = $request->param('id');
$key = "user:$id:api_count";
$limit = 10;
$check = Cache::exists($key);
if($check){
Cache::incr($key);
$count = Cache::get($key);
if($count > $limit){
exit('禁止频繁访问接口');
}
}else{
Cache::incr($key);
Cache::expire($key,60);
}
return $next($request);
}
|