有效地管理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中文網其他相關文章!