ekreative/ratelimit-bundle

此包已被废弃,不再维护。作者建议使用 noxlogic/ratelimit-bundle 包。

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

安装: 934

依赖: 0

建议者: 0

安全: 0

星级: 0

关注者: 3

分支: 70

类型:symfony-bundle

1.8.1 2018-05-25 06:29 UTC

README

Build Status Code Coverage Scrutinizer Code Quality

Latest Stable Version Total Downloads Latest Unstable Version License

此包提供了启用 @RateLimit 注解的功能,允许您限制对操作的连接数。这主要用于API。

默认情况下,此包已准备好与 FOSOAuthServerBundle 合作使用。它包含一个监听器,将OAuth令牌添加到缓存键。但是,您可以创建自己的键生成器以允许基于请求的自定义速率限制。请参阅下面的 创建自定义键生成器

此包部分受GitHub上Ruud Kamphuis的一个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"; "php_redis"

    # The redis client to use for the redis storage engine
    redis_client:         default_client
    
    # The Redis service, use this if you dont use SncRedisBundle and want to specify a service to use
    # Should be instance of \Predis\Client
    redis_service:    null # Example: project.predis

    # The Redis client to use for the php_redis storage engine
    # Should be an instance of \Redis
    php_redis_service:    null # Example: project.redis

    # The memcache client to use for the memcache storage engine
    memcache_client:      default
    
    # The Memcached service, use this if you dont use LswMemcacheBundle and want to specify a service to use
    # Should be instance of \Memcached
    memcache_service:    null # Example: project.memcached

    # The Doctrine Cache provider to use for the doctrine storage engine
    doctrine_provider:    null # Example: my_apc_cache
    
    # The Doctrine Cache service, use this if you dont use DoctrineCacheBundle and want to specify a service to use
    # Should be an instance of \Doctrine\Common\Cache\Cache
    doctrine_service:    null # Example: project.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
        
    # - { path: /api, limit: 1000, period: 3600 }
    # - { path: /dashboard, limit: 100, period: 3600, methods: ['GET', 'POST']}

    # Should the FOS OAuthServerBundle listener be enabled 
    fos_oauth_key_listener: true

使用说明

简单速率限制

要启用速率限制,您只需将注解添加到指定操作的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