instasent/ratelimit-bundle
Composer 安装命令:
composer require instasent/ratelimit-bundle
包简介
This bundle provides functionality to limit calls to actions based on rate limits
关键字:
README 文档
README
This bundle provides enables the @RateLimit annotation which allows you to limit the number of connections to actions.
This is mostly useful in APIs.
The bundle is prepared to work by default in cooperation with the FOSOAuthServerBundle. It contains a listener that adds the OAuth token to the cache-key. However, you can create your own key generator to allow custom rate limiting based on the request. See Create a custom key generator below.
This bundle is partially inspired by a GitHub gist from Ruud Kamphuis: https://gist.github.com/ruudk/3350405
Features
- Simple usage through annotations
- Customize rates per controller, action and even per HTTP method
- Multiple storage backends: Redis, Memcached and Doctrine cache
Installation
Installation takes just few easy steps:
Step 1: Add the bundle to your composer.json
If you're not yet familiar with Composer see http://getcomposer.org. Add the InstasentRateLimitBundle in your composer.json:
{ "require": { "Instasent/ratelimit-bundle": "1.x" } }
Now tell composer to download the bundle by running the command:
php composer.phar update Instasent/ratelimit-bundle
Step 2: Enable the bundle
Enable the bundle in the kernel:
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new Instasent\RateLimitBundle\InstasentRateLimitBundle(), ); }
Step 3: Install a storage engine
Redis
If you want to use Redis as your storage engine, you will need to install SncRedisBundle:
Memcache
If you want to use Memcache, you need to install LswMemcacheBundle
Doctrine cache
If you want to use Doctrine cache as your storage engine, you will need to install DoctrineCacheBundle:
Referer to their documentations for more details. You can change your storage engine with the storage_engine configuration parameter. See Configuration reference.
Configuration
Enable bundle only in production
If you wish to enable the bundle only in production environment (so you can test without worrying about limit in your development environments), you can use the enabled configuration setting to enable/disable the bundle completely. It's enabled by default:
# config_dev.yml instasent_rate_limit: enabled: false
Configuration reference
This is the default bundle configuration:
instasent_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
Usage
Simple rate limiting
To enable rate limiting, you only need to add the annotation to the docblock of the specified action
<?php use Instasent\RateLimitBundle\Annotation\RateLimit; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * @Route(...) * * @RateLimit(limit=1000, period=3600) */ public function someApiAction() { }
Limit per method
It's possible to rate-limit specific HTTP methods as well. This can be either a string or an array of methods. When no method argument is given, all other methods not defined are rated. This allows to add a default rate limit if needed.
<?php use Instasent\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() { }
Limit per controller
It's also possible to add rate-limits to a controller class instead of a single action. This will act as a default rate limit for all actions, except the ones that actually defines a custom rate-limit.
<?php use Instasent\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() { } }
Create a custom key generator
If you need to create a custom key generator, you need to register a listener to listen to the ratelimit.generate.key event:
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 Instasent\RateLimitBundle\Events\GenerateKeyEvent; class RateLimitGenerateKeyListener { public function onGenerateKey(GenerateKeyEvent $event) { $key = $this->generateKey(); $event->addToKey($key); // $event->setKey($key); // to overwrite key completely } }
Make sure to generate a key based on what is rate limited in your controllers.
Set custom period or limit
If you need to create a custom period/limit based for example on client settings saved in database, you need to register a listener to listen to the ratelimit.pre.create event:
services: mybundle.listener.rate_limit_pre_create: class: MyBundle\Listener\RateLimitFromDatabaseListener tags: - { name: kernel.event_listener, event: 'ratelimit.pre.create', method: 'findUserLimit' }
<?php namespace MyBundle\Listener; use Instasent\RateLimitBundle\Events\RateLimit; class RateLimitFromDatabaseListener { public function findUserLimit(RateLimit $event) { //TODO search value in database $event->setLimit($value); } }
Set your own limit value
Throwing exceptions
Instead of returning a Response object when a rate limit has exceeded, it's also possible to throw an exception. This
allows you to easily handle the rate limit on another level, for instance by capturing the kernel.exception event.
Running tests
If you want to run the tests use:
./vendor/bin/phpunit ./Tests
instasent/ratelimit-bundle 适用场景与选型建议
instasent/ratelimit-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 526 次下载、GitHub Stars 达 1, 最近一次更新时间为 2016 年 07 月 06 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「rest」 「api」 「x-rate-limit」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 instasent/ratelimit-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 instasent/ratelimit-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 instasent/ratelimit-bundle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
This bundle provides functionality to limit calls to actions based on rate limits
This bundle provides functionality to limit calls to actions based on rate limits
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
A Flickr wrapper to allow you to call the Flickr api with Guzzle as the backend.Goal is to have 100% Flickr api coverage rather than just upload/display photos (currently at 23%).
This bundle provides functionality to limit calls to actions based on rate limits
统计信息
- 总下载量: 526
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2016-07-06