muffin/throttle
Composer 安装命令:
composer require muffin/throttle
包简介
(API) Rate limiting requests in CakePHP
README 文档
README
(API) Rate limiting requests in CakePHP
This plugin allows you to limit the number of requests a client can make to your app in a given time frame.
Installation
composer require muffin/throttle
To make your application load the plugin either run:
./bin/cake plugin load Muffin/Throttle
Configuration
In your config/app.php add a cache config named throttle under the Cache key
with required config. For e.g.:
'throttle' => [ 'className' => 'Apcu', 'prefix' => 'throttle_' ],
Using the Middleware
Add the middleware to the queue and pass your custom configuration:
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { // Various other middlewares for error handling, routing etc. added here. $throttleMiddleware = new \Muffin\Throttle\Middleware\ThrottleMiddleware([ // Data used to generate response with HTTP code 429 when limit is exceeded. 'response' => [ 'body' => 'Rate limit exceeded', ], // Time period as number of seconds 'period' => 60, // Number of requests allowed within the above time period 'limit' => 100, // Client identifier 'identifier' => function ($request) { if (!empty($request->getHeaderLine('Authorization'))) { return str_replace('Bearer ', '', $request->getHeaderLine('Authorization')); } return $request->clientIp(); } ]); $middlewareQueue->add($throttleMiddleware); return $middlewareQueue; }
The above example would allow 100 requests/minute/token and would first try to identify the client by JWT Bearer token before falling back to (Throttle default) IP address based identification.
Events
The middleware also dispatches following event which effectively allows you to have multiple rate limits:
Throttle.beforeThrottle
This is the first event that is triggered before a request is processed by the middleware. All rate limiting process will be bypassed if this event is stopped.
\Cake\Event\EventManager::instance()->on( \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_BEFORE_THROTTLE, function ($event, $request) { if (/* check for something here, most likely using $request */) { $event->stopPropagation(); } } );
Throttle.getIdentifier
Instead of using the indentifer config you can also setup a listener for the
Throttle.getIdentifier event. The event's callback would receive a request
instance as argument and must return an identifier string.
Throttle.getThrottleInfo
The Throttle.getThrottleInfo event allows you to customize the period and limit
configs for a request as well as the cache key used to store the rate limiting info.
This allows you to set multiple rate limit as per your app's needs.
Here's an example:
\Cake\Event\EventManager::instance()->on( \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_GET_THROTTLE_INFO, function ($event, $request, \Muffin\Throttle\ValueObject\ThrottleInfo $throttle) { // Set a different period for POST request. if ($request->is('POST')) { // This will change the cache key from default "{identifer}" to "{identifer}.post". $throttle->appendToKey('post'); $throttle->setPeriod(30); } // Modify limit for logged in user $identity = $request->getAttribute('identity'); if ($identity) { $throttle->appendToKey($identity->get('role')); $throttle->setLimit(200); } } );
Throtttle.beforeCacheSet
The Throtttle.beforeCacheSet event allows you to observe result of middleware configuration and previous
Throtttle.getIdentifier and Throttle.getThrottleInfo events results.
You can also use this event to modify cached $rateLimit and $ttl values,
modifying $throttleInfo in this event has no effect.
Example:
\Cake\Event\EventManager::instance()->on( \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_BEFORE_CACHE_SET, function ($event, \Muffin\Throttle\ValueObject\RateLimitInfo $rateLimit, int $ttl, \Muffin\Throttle\ValueObject\ThrottleInfo $throttleInfo) { \Cake\Log\Log::debug(sprintf("key(%s) remaining(%d) resetTimestamp(%d) ttl(%d)", $throttleInfo->getKey(), $rateLimit->getRemaining(), $rateLimit->getResetTimestamp(), $ttl)); } );
X-headers
By default Throttle will add X-headers with rate limiting information to all responses:
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1438434161
To customize the header names simply pass (all of them) under headers key in
your configuration array:
'headers' => [ 'limit' => 'X-MyRateLimit-Limit', 'remaining' => 'X-MyRateLimit-Remaining', 'reset' => 'X-MyRateLimit-Reset', ]
To disable the headers set headers key to false.
Customize response object
You may use type and headers subkeys of the response array (as you would do
with a Response object) if you want to return a different message as the default one:
new \Muffin\Throttle\Middleware\ThrottleMiddleware([ 'response' => [ 'body' => json_encode(['error' => 'Rate limit exceeded']), 'type' => 'json', 'headers' => [ 'Custom-Header' => 'custom_value', ] ], 'limit' => 300, ]);
Patches & Features
- Fork
- Mod, fix
- Test - this is important, so it's not unintentionally broken
- Commit - do not mess with license, todo, version, etc. (if you do change any, bump them into commits of their own that I can ignore when I pull)
- Pull request - bonus point for topic branches
To ensure your PRs are considered for upstream, you MUST follow the CakePHP coding standards.
Bugs & Feedback
http://github.com/usemuffin/throttle/issues
License
Copyright (c) 2015-Present, [Use Muffin] and licensed under The MIT License.
muffin/throttle 适用场景与选型建议
muffin/throttle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 309.87k 次下载、GitHub Stars 达 62, 最近一次更新时间为 2015 年 06 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cakephp」 「throttle」 「limit」 「Rate」 「muffin」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 muffin/throttle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 muffin/throttle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 muffin/throttle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
CakePHP 4.x AdminLTE Theme.
Rapid pagination without using OFFSET
Limit number of records that can be added to a SilverStripe GridField
PHP PDO Mysql select statement iterator implemented as multiple queries using LIMIT clauses
Magento 2 Discount Amount Limiter
A Laravel Pulse card to track users & URL's that are being throttled by your Rate Limiters
统计信息
- 总下载量: 309.87k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 62
- 点击次数: 30
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-06-09