wellingguzman / rate-limit
dev-master / 1.0.x-dev
2019-02-22 21:28 UTC
Requires
- php: ^5.6 | ^7.0
- psr/http-message: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- phpunit/phpunit: ^4.7 | ^5.0
- zendframework/zend-diactoros: ^1.3
This package is auto-updated.
Last update: 2019-02-22 21:35:42 UTC
README
便于实现速率限制功能的组件。虽然设计为独立组件,但也提供适用于任何支持中间件概念的框架的API和/或其他应用端点的中间件。
基于 nikolaposa/rate-limit
。移除了类型提示和 declare
函数以支持PHP 5.6。
安装
推荐通过 Composer 进行安装。运行以下命令安装最新版本的软件包并将其添加到项目的 composer.json
文件中
composer require wellingguzman/rate-limit
使用
独立
$rateLimiter = \RateLimit\RateLimiterFactory::createInMemoryRateLimiter(1000, 3600); echo $rateLimiter->getLimit(); //1000 echo $rateLimiter->getWindow(); //3600 $rateLimiter->hit('key'); echo $rateLimiter->getRemainingAttempts('key'); //999 echo $rateLimiter->getResetAt('key'); //1486503558
注意:内存速率限制器仅应用于测试目的。此软件包还提供基于Redis的速率限制器
$rateLimiter = \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([ 'host' => '10.0.0.7', 'port' => 6379, ], 1000, 3600);
中间件
Zend Expressive 示例
$app = \Zend\Expressive\AppFactory::create(); $app->pipe(\RateLimit\Middleware\RateLimitMiddleware::createDefault( \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([ 'host' => '10.0.0.7', 'port' => 6379, ], 1000, 3600) ));
Slim 示例
$app = new \Slim\App(); $app->add(\RateLimit\Middleware\RateLimitMiddleware::createDefault( \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([ 'host' => '10.0.0.7', 'port' => 6379, ], 1000, 3600) ));
白名单请求
use Psr\Http\Message\RequestInterface; $rateLimitMiddleware = \RateLimit\Middleware\RateLimitMiddleware::createDefault( \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([ 'host' => '10.0.0.7', 'port' => 6379, ], 1000, 3600), [ 'whitelist' => function (RequestInterface $request) { if (false !== strpos($request->getUri()->getPath(), 'admin')) { return true; } return false; }, ] );
自定义超过限制的处理程序
use Psr\Http\Message\RequestInterface; use Zend\Diactoros\Response\JsonResponse; $rateLimitMiddleware = \RateLimit\Middleware\RateLimitMiddleware::createDefault( \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([ 'host' => '10.0.0.7', 'port' => 6379, ], 1000, 3600), [ 'limitExceededHandler' => function (RequestInterface $request) { return new JsonResponse([ 'message' => 'API rate limit exceeded', ], 429); }, ] );
作者
Nikola Poša
版权和许可
版权所有2017 Nikola Poša。在MIT许可证下发布 - 有关详细信息,请参阅 LICENSE
文件。