Laravel queue rate limiting or throttling

后端 未结 6 1310
南方客
南方客 2020-12-11 17:19

I am working on an app that requires fetching data from a third-party server and that server allows max 1 request per seconds.

Now, all request send as job and I am

6条回答
  •  抹茶落季
    2020-12-11 17:33

    I'm the author of mxl/laravel-queue-rate-limit Composer package.

    It allows you to rate limit jobs on specific queue without using Redis.

    1. Install it with:

      $ composer require mxl/laravel-queue-rate-limit:^1.0
      
    2. This package is compatible with Laravel 5.5+ and uses auto-discovery feature to add MichaelLedin\LaravelQueueRateLimit\QueueServiceProvider::class to providers.

    3. Add rate limit settings to config/queue.php:

      'rateLimit' => [
          'mail' => [
              'allows' => 1,
              'every' => 5
          ]
      ]
      

      These settings allow to run 1 job every 5 seconds on mail queue. Make sure that default queue driver (default property in config/queue.php) is set to any value except sync.

    4. Run queue worker with --queue mail option:

      $ php artisan queue:work --queue mail
      

      You can run worker on multiple queues, but only queues referenced in rateLimit setting will be rate limited:

      $ php artisan qeueu:work --queue mail,default
      

      Jobs on default queue will be executed without rate limiting.

    5. Queue some jobs to test rate limiting:

      SomeJob::dispatch()->onQueue('mail');
      SomeJob::dispatch()->onQueue('mail');
      SomeJob::dispatch()->onQueue('mail');
      SomeJob::dispatch();
      

提交回复
热议问题