精细化/速率限制包

此包提供了基于速率限制调用操作的功能

安装: 30

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 74

类型:symfony-bundle

1.7.0 2016-03-29 20:56 UTC

This package is not auto-updated.

Last update: 2024-09-23 06:26:50 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

Latest Stable Version Total Downloads Latest Unstable Version License

此包提供了 @RateLimit 注解,允许您限制对操作的连接数。这在API中非常有用。

默认情况下,该包已准备与 FOSOAuthServerBundle 协作工作。它包含一个监听器,该监听器会将OAuth令牌添加到缓存键。但是,您可以根据请求创建自己的键生成器以实现基于请求的定制速率限制。请参阅下面的 创建自定义键生成器

此包部分受到Ruud Kamphuis在GitHub上发布的一个gist的启发:https://gist.github.com/ruudk/3350405

特性

  • 通过注解简单使用
  • 可以按控制器、操作甚至按HTTP方法自定义速率
  • 多个存储后端:Redis、Memcached和Doctrine缓存

安装

安装只需几个简单的步骤

步骤1:将包添加到您的composer.json文件中

如果您还不熟悉Composer,请参阅 https://getcomposer.org.cn。在您的composer.json中添加NoxlogicRateLimitBundle

{
    "require": {
        "noxlogic/ratelimit-bundle": "1.x"
    }
}

现在运行以下命令告诉Composer下载包:

php composer.phar update noxlogic/ratelimit-bundle

步骤2:启用包

在内核中启用包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Noxlogic\RateLimitBundle\NoxlogicRateLimitBundle(),
    );
}

步骤3:安装存储引擎

Redis

如果您想使用Redis作为存储引擎,则需要安装 SncRedisBundle

Memcache

如果您想使用Memcache,则需要安装 LswMemcacheBundle

Doctrine缓存

如果您想使用Doctrine缓存作为存储引擎,则需要安装 DoctrineCacheBundle

请参考他们的文档以获取更多详细信息。您可以通过 storage_engine 配置参数更改存储引擎。请参阅 配置参考

配置

仅在生产环境中启用包

如果您只想在生产环境中启用包(这样您就可以在开发环境中测试而不用担心限制),您可以使用 enabled 配置设置来完全启用或禁用包。默认情况下已启用

# config_dev.yml
noxlogic_rate_limit:
    enabled: false

配置参考

这是默认包配置

noxlogic_rate_limit:
    enabled:              true

    # The storage engine where all the rates will be stored
    storage_engine:       ~ # One of "redis"; "memcache"; "doctrine"

    # The redis client to use for the redis storage engine
    redis_client:         default_client

    # The memcache client to use for the memcache storage engine
    memcache_client:      default

    # The Doctrine Cache provider to use for the doctrine storage engine
    doctrine_provider:    null # Example: my_apc_cache

    # The HTTP status code to return when a client hits the rate limit
    rate_response_code:   429

    # Optional exception class that will be returned when a client hits the rate limit
    rate_response_exception:  null

    # The HTTP message to return when a client hits the rate limit
    rate_response_message:  'You exceeded the rate limit'

    # Should the ratelimit headers be automatically added to the response?
    display_headers:      true

    # What are the different header names to add
    headers:
        limit:                X-RateLimit-Limit
        remaining:            X-RateLimit-Remaining
        reset:                X-RateLimit-Reset

    # Rate limits for paths
    path_limits:
        path:                 ~ # Required
        methods:

            # Default:
            - *
        limit:                ~ # Required
        period:               ~ # Required

使用方法

简单速率限制

要启用速率限制,您只需将注解添加到指定操作的docblock中即可

<?php

use Noxlogic\RateLimitBundle\Annotation\RateLimit;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route(...)
 *
 * @RateLimit(limit=1000, period=3600)
 */
public function someApiAction()
{
}

按方法限制

还可以对特定的HTTP方法进行速率限制。这可以是字符串或方法数组。如果没有指定方法参数,则所有未定义的方法都将受到速率限制。这允许添加默认速率限制(如果需要的话)。

<?php

use Noxlogic\RateLimitBundle\Annotation\RateLimit;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route(...)
 *
 * @RateLimit(methods={"PUT", "POST"}, limit=1000, period=3600)
 * @RateLimit(methods={"GET"}, limit=1000, period=3600)
 * @RateLimit(limit=5000, period=3600)
 */
public function someApiAction()
{
}

按控制器限制

还可以将速率限制添加到控制器类而不是单个操作。这将作为所有操作的默认速率限制,除非实际定义了自定义速率限制。

<?php

use Noxlogic\RateLimitBundle\Annotation\RateLimit;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Ratelimit(methods={"POST"}, limit=100, period=10); // 100 POST requests per 10 seconds
 */
class DefaultController extends Controller
{
    /**
     * @ratelimit(method="POST", limit=200, period=10); // 200 POST requests to indexAction allowed.
     */
    public function indexAction()
    {
    }
}

创建自定义键生成器

如果您需要创建自定义键生成器,则需要注册一个监听器来监听 ratelimit.generate.key 事件

services:
    mybundle.listener.rate_limit_generate_key:
        class: MyBundle\Listener\RateLimitGenerateKeyListener
        tags:
            - { name: kernel.event_listener, event: 'ratelimit.generate.key', method: 'onGenerateKey' }
<?php

namespace MyBundle\Listener;

use Noxlogic\RateLimitBundle\Events\GenerateKeyEvent;

class RateLimitGenerateKeyListener
{
    public function onGenerateKey(GenerateKeyEvent $event)
    {
        $key = $this->generateKey();

        $event->addToKey($key);
        // $event->setKey($key); // to overwrite key completely
    }
}

请确保根据控制器中速率限制的内容生成键。

抛出异常

当超出速率限制时,不仅可以返回一个响应对象,还可以抛出异常。这允许您在另一个级别上轻松处理速率限制,例如通过捕获 kernel.exception 事件。

运行测试

如果您想运行测试,请使用

./vendor/bin/phpunit ./Tests