perimeter/rate-limit-bundle

Perimeter RateLimitBundle

安装: 1,456

依赖: 0

建议者: 1

安全: 0

星标: 41

关注者: 4

分支: 4

公开问题: 0

类型:symfony-bundle

v0.1.7 2015-04-10 20:57 UTC

This package is not auto-updated.

Last update: 2024-09-10 02:36:25 UTC


README

Build Status

基于独立的速率限制库 rate-limiter-php 构建

限制这些API的速率!

安装

$ composer.phar require perimeter/rate-limit-bundle:dev-develop

开始使用

此库帮助您以两种方式限制API的速率

  • 速率限制警告 - 在响应中发出 X-RATELIMIT-WARNING 标头,但否则调用不受影响。
  • 速率限制超出 - 返回HTTP状态码 429 Too Many Requests,并限制调用。

配置您的计费存储

最简单的选项是使用 MemoryStorage 进行计费配置。默认情况下,警告标头在 每小时80次调用 时发出,并在 每小时100次调用 时限制响应。您可以在服务容器中更改这些基本默认值

<parameters>
    <parameter key="perimeter.rate_limit.warn_threshold.default">45000</parameter>
    <parameter key="perimeter.rate_limit.limit_threshold.default">50000</parameter>
</parameters>

现在将警告并限制用户每小时 45,00050,000 次调用。您还可以根据认证用户自定义不同的计费器

<parameters>
    <parameter key="perimeter.rate_limit.storage.memory.meters" type="collection">
        <parameter key="*" type="collection">
            <parameter key="warn_threshold">%perimeter.rate_limit.warn_threshold.default%</parameter>
            <parameter key="limit_threshold">%perimeter.rate_limit.limit_threshold.default%</parameter>
        </parameter>
        <parameter key="bshaffer" type="collection">
            <parameter key="warn_threshold">150</parameter>
            <parameter key="limit_threshold">200</parameter>
        </parameter>
    </parameter>
</parameters>

这意味着任何使用用户名 bshaffer 认证的调用将警告 150/小时 并限制在 200/小时 而不是默认值。如果您计划按用户名进行速率限制,强烈建议使用 Doctrine Meter Storage

Doctrine Meter Storage(高级)

Doctrine计费存储是配置计费器的最佳方式。首先,运行命令在您的数据库中创建表

php vendor/doctrine/orm/bin/doctrine orm:schema-tool:update --force

其次,您需要配置容器以使用Doctrine存储引擎

<services>
    <!-- ... -->
    <service id="perimeter.rate_limit.storage" alias="perimeter.rate_limit.storage.doctrine" />
<services>

接下来,您将想要在您的Doctrine数据库中创建计费器。例如,使用 perimeter:rate-limit-meter 命令执行此操作

$ ./bin/console perimeter:rate-limit-meter * 80 100

使用Doctrine计费存储时,必须 配置 default meter。上面的命令将创建默认计费器,警告 80 calls/hour 并在 100 calls/hr 时限制速率。

您可以使用 perimeter:rate-limit-meter 命令查看、创建、更新和删除计费器。还有一个 MeterApiController 提供了JSON/XML API以执行此操作。

配置您的限速器

默认情况下,此库使用 RedisThrottler 来跟踪击中和桶。如果 Redis 不可用于限速,您也可以使用 DoctrineThrottler,尽管不推荐这样做,因为 Redis 对此类操作更合适。

Redis限速器(默认)

此库默认使用Redis。要开始使用Redis限速器,只要Redis在 localhost:6379 上运行,您就无需做任何事情!如果您的Redis服务器在别处运行,只需配置容器中的 perimeter.rate_limit.redis_client.url 指向正确的宿主和端口即可。

Doctrine限速器

请确保运行以下命令以在您的数据库中创建 rate_limit_bucket

php vendor/doctrine/orm/bin/doctrine orm:schema-tool:update --force

现在,通过将限速器服务ID配置为doctrine限速器的别名来配置容器以使用 Perimeter\RateLimiter\Throttler\DoctrineThrottler

<services>
    <!-- ... -->
    <service id="perimeter.rate_limit.throttler" alias="perimeter.rate_limit.throttler.doctrine" />
<services>