有效地管理API速率限制至关重要。 Laravel使用Redis::throttle
提供了简化的解决方案,以控制排队的作业的流动,防止API洪水和潜在的服务中断。 让我们探索实施的实施。
利用Redis::throttle
>提供了一种强大的机制来调节排队的工作执行。这样可以确保遵守API率限制,避免临时或永久服务块。 基本结构如下:Redis::throttle
Redis::throttle('key-name') ->allow(10) // Allow 10 requests ->every(5) // Within a 5-second window ->then(function () { // Your job logic here });
实践:AWS SES电子邮件交付>
>让我们创建一个中间件系统,用于管理使用AWS SES的电子邮件发送费率:此中间件将应用于我们的电子邮件通知系统:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Redis; class EmailRateLimit { public function handle($job, Closure $next) { Redis::throttle('email-throttle') ->allow(10) ->every(2) ->block(2) // Wait 2 seconds if throttled ->then(function () use ($job, $next) { $next($job); }, function () use ($job) { $job->release(30); // Release after 30 seconds }); } }
最后,将其集成到控制器中:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; use App\Http\Middleware\EmailRateLimit; class EmailDispatch extends Notification implements ShouldQueue { use Queueable; public $content; public function __construct($content) { $this->content = $content; } // ... (rest of the Notification class remains the same) ... public function middleware(): array { return [new EmailRateLimit]; } }这种全面的方法可确保您的申请尊重API率限制,同时通过AWS SES或任何兼容的电子邮件服务提供商保持有效的电子邮件交付。 中间件的使用将限制逻辑与您的核心应用程序代码分开。
以上是通过工作节流管理Laravel的API率限制的详细内容。更多信息请关注PHP中文网其他相关文章!