coon-design / rate-limit
PSR-7 速率限制实现
0.5
2023-06-03 11:03 UTC
Requires
- php: >=5.4.0
- ptrofimov/tinyredisclient: ^1.1
- slim/psr7: ^1.6
This package is auto-updated.
Last update: 2024-10-03 13:49:40 UTC
README
PSR-7 速率限制使用 Redis 或 Memcache。此中间件不需要 predis。它使用 ptrofimov 的 Tinyredisclient。
使用方法
最后一个构造函数参数是 Redis 密码。这是可选的。如果没有提供,中间件将未进行身份验证而连接。
$rateLimitMiddleware = new \Prezto\RateLimit\RateLimitMiddleware('10.241.25.226', '6379', 'aslkjkrnflawekrmgfslerm')
实例化后设置限制。第一个参数是最大请求数量。第二个参数是时间限制(秒)。
在此示例中,客户端被允许在 30 秒内发起 60 个请求。
$rateLimitMiddleware->setRequestsPerSecond(60, 30);
当达到请求限制时,默认将请求状态码设置为 429。
默认使用 Redis 作为存储。要使用 Memcache 代替
$rateLimitMiddleware->useMemcache();
达到限制时的自定义处理程序。
$rateLimitMiddleware->setHandler(function ($request, $response) { $response = $response->withStatus(429); $response->getBody()->write("Rate limit reached."); return $response; });