【问题标题】:Laravel - Task Scheduling or Queue?Laravel - 任务调度或队列?
【发布时间】:2021-10-09 22:11:09
【问题描述】:

在我的 Laravel 应用程序中,用户可以对提交的内容投赞成票或反对票。

为了计算提交的总分,我不会在每次投票时都这样做,因为这会导致大量查询。

相反,每隔几分钟,我使用 Laravel 的任务调度器运行一个任务,获取所有最近提交的内容,然后计算每个提交的总分。

任务命令:

$submissions = Submission::where('created_at', '>', Carbon::now()->subDays(2))
    ->withCount('upVotes')
    ->withCount('downVotes')
    ->get();

$submissions->each(function ($item) {
    $item->total_upvotes = $item->up_votes_count;
    $item->total_downvotes = $item->down_votes_count;
    $item->total_score = $this->score($item->up_votes_count, $item->down_votes_count);
    $item->hotness = $this->hotness($item->up_votes_count, $item->down_votes_count, $item->created_at->timestamp);
    $item->save();
});

但是,我担心当扩展到每天可能有数千个提交时,这可能无法很好地工作。也许这个任务会超时?

或者,我可以让命令调度一个执行 foreach 的作业,而不是在任务调度程序命令中执行 foreach,如下所示:

任务命令:

$submissions = Submission::where('created_at', '>', Carbon::now()->subDays(2))
    ->withCount('upVotes')
    ->withCount('downVotes')
       ->get();

//DISPATCH QUEUE JOB

队列作业:

$submissions->each(function ($item) {
    $item->total_upvotes = $item->up_votes_count;
    $item->total_downvotes = $item->down_votes_count;
    $item->total_score = $this->score($item->up_votes_count, $item->down_votes_count);
    $item->hotness = $this->hotness($item->up_votes_count, $item->down_votes_count, $item->created_at->timestamp);
    $item->save();
});

这样会更好吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    是的 - 那会更好。

    我有一个工作量相似的项目,我从外部仓库 API 下载数千种产品,并逐个浏览以更新实时产品的价格、图像和描述。这也是在单个 for 循环中完成时需要很长时间的事情,而且单个作业肯定是不够的。

    我使用 Laravel Horizo​​n 来处理我的队列,并为许多不同的操作(处理、邮寄等)设置了单独的队列。数据处理队列最多同时运行 10 个作业,这使得它比单个 for 循环作业更快。

    【讨论】:

    • 您应该为每次提交排队作业。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多