fusonic / rate-limit-bundle

基于路由的简单速率限制。

v4.0.0 2020-12-11 11:12 UTC

This package is auto-updated.

Last update: 2024-09-11 19:11:39 UTC


README

此包提供基于路由的简单速率限制。

入门

  1. 安装包
composer require fusonic/rate-limit-bundle
  1. 将 RateLimitBundle 添加到内核
    Fusonic\RateLimitBundle\RateLimitBundle::class => ['prod' => true],
  1. 添加缓存配置
framework:
    cache:
        app: cache.adapter.array
  1. 添加速率限制配置
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