spatie/laravel-rate-limited-job-middleware
Composer 安装命令:
composer require spatie/laravel-rate-limited-job-middleware
包简介
A middleware that can rate limit jobs
README 文档
README
This package contains a job middleware that can rate limit jobs in Laravel apps.
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
You can install the package via composer:
composer require spatie/laravel-rate-limited-job-middleware
Usage
By default, the middleware will only allow 5 jobs to be executed per second. Any jobs that are not allowed will be released for 5 seconds.
To apply the middleware just add the Spatie\RateLimitedMiddleware\RateLimited to the middlewares of your job.
namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Spatie\RateLimitedMiddleware\RateLimited; class TestJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable; public function handle() { // your job logic } public function middleware() { return [new RateLimited()]; } }
Configuring attempts
When using rate limiting, the number of attempts of your job may be hard to predict. Instead of using a fixed number of attempts, it's better to use time based attempts.
You can add this to your job class:
/* * Determine the time at which the job should timeout. * */ public function retryUntil() : \DateTime { return now()->addDay(); }
Customizing the behaviour
You can customize all the behaviour. Here's an example where the middleware allows a maximum of 30 jobs to performed in a timespan of 60 seconds. Jobs that are not allowed will be released for 90 seconds.
// in your job public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->allow(30) ->everySeconds(60) ->releaseAfterSeconds(90); return [$rateLimitedMiddleware]; }
Implementing Exponential Backoff
Often remote services such as APIs have rate limits or otherwise respond with a server error. Under these circumstances it makes sense to increment our delay before trying again. You can replace releaseAfter methods with releaseAfterBackoff($this->attempts() to use the default Rate Limiter interval of 5 seconds. Otherwise, you may chain the releaseAfter calls to adjust the backoff interval.
Example: releaseAfterOneMinute()
// in your job /** * Attempt 1: Release after 60 seconds * Attempt 2: Release after 180 seconds * Attempt 3: Release after 420 seconds * Attempt 4: Release after 900 seconds */ public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->allow(30) ->everySeconds(60) ->releaseAfterOneMinute() ->releaseAfterBackoff($this->attempts()); return [$rateLimitedMiddleware]; }
Example: releaseAfterSeconds()
// in your job /** * Attempt 1: Release after 5 seconds * Attempt 2: Release after 15 seconds * Attempt 3: Release after 35 seconds * Attempt 4: Release after 75 seconds */ public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->allow(30) ->everySeconds(60) ->releaseAfterSeconds(5) ->releaseAfterBackoff($this->attempts()); return [$rateLimitedMiddleware]; }
Example: Customize Backoff Rate
releaseAfterBackoff() accepts the rate multiplier as the second argument. By default, the multiplier is 2.
Below is an example of setting the rate to 3. You'll notice that as the attempts grow, the difference between a rate of 2 vs. a rate of 3 becomes significantly greater.
// in your job /** * Attempt 1: Release after 5 seconds * Attempt 2: Release after 20 seconds * Attempt 3: Release after 65 seconds * Attempt 4: Release after 200 seconds */ public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->allow(30) ->everySeconds(60) ->releaseAfterBackoff($this->attempts(), 3); return [$rateLimitedMiddleware]; }
Not releasing jobs
If you don't want to retry a job when it is ratelimited, you can use the dontRelease() method. This is useful in situations where you have jobs that run periodically and you don't care about a job being skipped.
public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->allow(30) ->everySeconds(60) ->dontRelease(); return [$rateLimitedMiddleware]; }
Customizing Redis
By default, the middleware will use the default Redis connection.
The default key that will be used in redis will be the name of the class that created the instance of the middleware. In most cases this will be name of job in which the middleware is applied. If this is not what you expect, you can use the key method to customize it.
Here's an example where a custom connection and custom key is used.
// in your job public function middleware() { $rateLimitedMiddleware = (new RateLimited()) ->connectionName('my-custom-connection') ->key('my-custom-key'); return [$rateLimitedMiddleware]; }
Conditionally applying the middleware
If you want to conditionally apply the middleware you can use the enabled method. If accepts a boolean that determines if the middleware should rate limit your job or not.
You can also pass a Closure to enabled. If it evaluates to a truthy value the middleware will be enable.
Here's a silly example where the rate limiting is only activated in January.
// in your job public function middleware() { $shouldRateLimitJobs = Carbon::now()->month === 1; $rateLimitedMiddleware = (new RateLimited()) ->enabled($shouldRateLimitJobs); return [$rateLimitedMiddleware]; }
Available methods.
These methods are available to be called on the middleware. Their names should be self-explanatory.
allow(int $allowedNumberOfJobsInTimeSpan)everySecond(int $timespanInSeconds = 1)everySeconds(int $timespanInSeconds)everyMinute(int $timespanInMinutes = 1)everyMinutes(int $timespanInMinutes)releaseAfterOneSecond()releaseAfterSeconds(int $releaseInSeconds)releaseAfterOneMinute()releaseAfterMinutes(int $releaseInMinutes)releaseAfterRandomSeconds(int $min = 1, int $max = 10)
Available events.
\Spatie\RateLimitedMiddleware\Events\LimitExceededwhen the rate limit has been exceeded.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.
Postcardware
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
We publish all received postcards on our company website.
Credits
This code is heavily based on the rate limiting example found in the Laravel docs.
License
The MIT License (MIT). Please see License File for more information.
spatie/laravel-rate-limited-job-middleware 适用场景与选型建议
spatie/laravel-rate-limited-job-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.4M 次下载、GitHub Stars 达 354, 最近一次更新时间为 2019 年 09 月 28 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「spatie」 「laravel-rate-limited-job-middleware」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 spatie/laravel-rate-limited-job-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 spatie/laravel-rate-limited-job-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 spatie/laravel-rate-limited-job-middleware 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Receive webhooks in Laravel apps
Easily optimize images using PHP
Store your application settings
Add tags and taggable behaviour to your Laravel app
Speed up a Laravel application by caching the entire response additions
Manage events on a Google Calendar
统计信息
- 总下载量: 4.4M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 357
- 点击次数: 25
- 依赖项目数: 9
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-09-28