【问题标题】:How to lock the job during execution in Laravel?如何在 Laravel 执行期间锁定作业?
【发布时间】:2020-07-21 06:15:55
【问题描述】:

我看到 withoutOverlapping() 互斥锁用于命令,但我看不到它用于作业。如何防止同一类型的作业相互重叠?

谢谢!

【问题讨论】:

    标签: laravel mutex jobs


    【解决方案1】:

    我认为可以使用以下方法: https://laravel.com/docs/8.x/queues#unique-jobs

    您可以指定所需的密钥,您可以将其传递给作业以标记其唯一性。就我而言,我需要将请求限制在作业中发生的第三方 API,因此如果我有多个工作人员处理队列,则可以从 API 获得 429。只要我有许多 API 密钥(应用程序的每个用户),我就可以使用它在应用程序用户之间独立执行相同类型的作业,但如果具有特定密钥的当前作业不是,则锁定作业执行完成。

    像这样:

        //In the class defining you must use ShouldBeUnique interface
        class UpdateSpreadsheet implements ShouldQueue, ShouldBeUnique
        
        //some other code
            
        public function __construct($keyValue)
        {
        //some other constructor code if needed
        $this->keyValue= $keyValue;
        }
    
        //This function allows to set the unique key
        public function uniqueId()
        {
            return $this->keyValue;
        }
    
        //If you don't need to wait until the job is processed, you may also specify
        //the time for the force lock removing (so you'll be able to queue another 
        //job with this key after 10 seconds even if the current job is
        //still in process)
        
        public $uniqueFor = 10;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-01
      • 2013-10-07
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多