使用ThinkPHP框架实现API访问频率限制可以采用以下步骤:
安装topthink/think-redis
包来使用Redis服务。
composer require topthink/think-redis
在config/redis.php
中配置Redis连接信息。
return [
// 默认使用的数据库
'default' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
],
];
创建一个中间件app\middleware\CheckApiFrequency.php
,用于检查API访问频率。在中间件中,可以使用Redis
来存储API访问次数和时间戳信息,并根据限制条件判断是否允许继续访问。
<?php
namespace app\middleware;
use think\facade\Cache; use think\facade\Request; use think\facade\Config; use think\response\Json;
class CheckApiFrequency { public function handle($request, \Closure $next) { $key = $this->getCacheKey($request); $cache = Cache::store('redis');
$limit = Config::get('api_frequency.limit', 10);
$duration = Config::get('api_frequency.duration', 60);
$interval = floor(time() / $duration);
$count = $cache->get("$key:$interval", 0);
$cache->set("$key:$interval", $count + 1, $duration);
if ($count >= $limit) {
return Json::create(['code' => 429, 'msg' => 'Too Many Requests'], 'json', 429);
}
return $next($request);
}
private function getCacheKey($request)
{
$ip = $request->ip();
$url = $request->baseUrl();
$agent = $request->header('user-agent');
return md5("$ip:$url:$agent");
}
}
4. 在`config/middleware.php`中注册中间件。
```php
return [
'CheckApiFrequency' => app\middleware\CheckApiFrequency::class,
];
middleware
属性指定中间件。Route::get('api/user/:id', 'api/User/read')
->middleware('CheckApiFrequency');
关键词:
ThinkPHP框架
:PHP Web开发框架。API访问频率限制
:限制API接口的访问次数和时间间隔。Redis
:一种内存数据库,用于存储数据并提供高速读写访问。中间件
:在请求处理过程中执行的一些代码,用于实现各种功能,例如认证、授权、日志、缓存等。限制条件
:限制API访问的条件,例如每分钟最多访问次数、每小时最多访问次数等。路由
:用于定义URL与对应的处理方法之间的映射关系。