亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以限制每月的計劃 API 調用和每分鐘/小時的 API 調用嗎?

我可以限制每月的計劃 API 調用和每分鐘/小時的 API 調用嗎?

PHP
一只名叫tom的貓 2022-07-16 16:54:54
我想使用 Laravel Spark 為 API 創建不同的許可證。我想限制每月和每小時/每分鐘的 API 調用。例如,基本許可證將允許每月 10 000 次 API 調用,但我還想限制同一帳戶每小時/分鐘的 API 調用。這可以用 laravel spark 完成嗎?有:throttle 和 rate_limit,但我可以限制每月以及每小時/分鐘的 API 調用總數嗎?例如:每月總共 10 000 次 API 調用,每小時/分鐘最多 60 次 API 調用?根據文檔,我可以限制每分鐘/小時的訪問:https ://laravel.com/docs/6.x/routing#rate-limiting像這樣的東西結合了油門和速率限制:Route::middleware('auth:api', 'throttle:10|rate_limit,1')->group(function () {     Route::get('/user', function () { // }); });但我的主要問題是如何將每分鐘/小時的速率限制與每月限制結合起來?
查看完整描述

1 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

從同一文檔頁面:


您也可以將此功能與動態速率限制結合使用。例如,如果您的User模型包含一個rate_limit屬性,您可以將屬性的名稱傳遞給throttle中間件,以便用于計算經過身份驗證的用戶的最大請求數


因此,鑒于上述情況,您可以在模型上添加一個訪問器User,該訪問器根據他們當前的訂閱計劃獲取速率限制值:


class User extends Authenticatable

{

    public function getRateLimitAttribute()

    {

        // Get license if it's a model


        if ($license === 'basic') {

            return 10000;

        }


        // Return some default here

    }

}

然后,您可以像這樣使用動態速率限制值:


Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {

    // Rate-limited routes

});

至于每月限額,您需要在某處保留一個柜臺,并在每個請求時檢查。您可以在另一個中間件中記錄每個 API 請求:


class LogRequest

{

    public function handle($request, Closure $next)

    {

        return $next($request);

    }


    public function terminate($request, $response)

    {

        LogRequestJob::dispatch($request);

    }

}

class LogRequestJob implements ShouldQueue

{

    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    public function __construct(Request $request)

    {

        $this->request = $request;

    }


    public function handle()

    {

        // Insert row for user to log request

        RequestLog::create([

            'user_id' => $this->request->user()->getKey(),

            'path' => $this->request->path(),

            // Store any other request data you're interested in

        ]);

    }

}

然后,您需要在處理請求之前檢查計數,再次使用中間件:


use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;


class CheckRequestInLimit

{

    public function handle($request, Closure $next)

    {

        $year = Carbon::now()->year;

        $month = Carbon::now()->month;

        $count = RequestLog::user($request->user())->year($year)->month($month)->count();

        $limit = $request->user()->monthly_limit; // another accessor


        if ($count < $limit) {

            return $next($request);

        }


        // Count is equal to (or greater than) limit; throw exception

        $retryAfter = Carbon::today()->addMonth()->startOfMonth();

        $message = 'You have exceeded your monthly limit';


        throw new TooManyRequestsHttpException($retryAfter, $message);

    }

}

希望這能讓您深思!


2021 年 11 月 1 日編輯:此答案是針對舊版本的 Laravel 編寫的。Laravel 后來引入了速率限制,這將為上述問題提供更簡潔的解決方案:


RateLimiter::for('api', function (Request $request) {

    return [

        Limit::perHour(60)->by($request->user()->getKey()),

        Limit::perDay(10000, 30)->by($request->user()->getKey()),

    ];

});


查看完整回答
反對 回復 2022-07-16
  • 1 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號