首頁 > 後端開發 > php教程 > 通過工作節流管理Laravel的API率限制

通過工作節流管理Laravel的API率限制

James Robert Taylor
發布: 2025-03-06 01:44:08
原創
324 人瀏覽過

Managing API Rate Limits in Laravel Through Job Throttling

與AWS SES這樣的外部服務集成以進行電子郵件發送時,

有效地管理API速率限制至關重要。 Laravel使用Redis::throttle提供了簡化的解決方案,以控制排隊的作業的流動,防止API洪水和潛在的服務中斷。 讓我們探索實施的實施。

利用Redis::throttle

> Laravel's

>提供了一種強大的機制來調節排隊的工作執行。這樣可以確保遵守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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板