fusonic / rate-limit-bundle
基于路由的简单速率限制。
v4.0.0
2020-12-11 11:12 UTC
Requires
- php: >=7.4
- psr/log: ^1.1
- symfony/cache: ^4.4 || ^5.0
- symfony/config: ^4.4 || ^5.0
- symfony/dependency-injection: ^4.4 || ^5.0
- symfony/event-dispatcher: ^4.4 || ^5.0
- symfony/framework-bundle: ^4.4 || ^5.0
- symfony/http-foundation: ^4.4 || ^5.0
- symfony/http-kernel: ^4.4 || ^5.0
- symfony/monolog-bridge: ^4.4 || ^5.0
- symfony/monolog-bundle: ^3.5
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.17
- phpstan/phpstan: ^0.11 || ^0.12.50
- symfony/browser-kit: ^4.4 || ^5.0
- symfony/phpunit-bridge: ^4.4 || ^5.0
- symfony/yaml: ^4.4 || ^5.0
README
此包提供基于路由的简单速率限制。
入门
- 安装包
composer require fusonic/rate-limit-bundle
- 将 RateLimitBundle 添加到内核
Fusonic\RateLimitBundle\RateLimitBundle::class => ['prod' => true],
- 添加缓存配置
framework: cache: app: cache.adapter.array
- 添加速率限制配置
fusonic_rate_limit: cache_provider: "cache.app" enabled: true routes: foo: limit: 2 period: 3600
它是如何工作的
此包利用 Symfony 的事件系统。因此,一些事件位于 Fusonic/RateLimitBundle/Event
下。
- 当检测到速率限制路由的请求时,将发出 RateLimitAttemptsUpdatedEvent。
- 当超过路由限制时,将发出 RateLimitExceededEvent。
- RateLimitResetAttemptsEvent 可以用于重置特定路由的状态(例如,在成功登录后)。
示例
创建事件监听器或订阅者
<?php namespace AppBundle\EventListener; use Fusonic\RateLimitBundle\Event\RateLimitEvents; use Fusonic\RateLimitBundle\Event\RateLimitExceededEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; final class RateLimitSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ RateLimitEvents::ROUTE_LIMIT_EXCEEDED => 'onLimitExceeded', ]; } public function onLimitExceeded(RateLimitExceededEvent $event): void { $config = $event->getRouteLimitConfig(); $message = 'You sent too many requests for this endpoint.'; throw new TooManyRequestsHttpException($config->getPeriod(), $message); } }
并将其注册为服务。
app.rate_limit_subscriber: class: AppBundle\EventListener\RateLimitSubscriber tags: - { name: kernel.event_subscriber }
执行测试
通过执行以下命令运行测试
vendor/bin/simple-phpunit