Laravel 运行 artisan 命令每 5 秒

Laravel run artisan command every 5 seconds

我正在使用一个系统,只要该系统中的资源发生变化,它就会向我发送 webhook。 Webhook 包含已更新资源的 ID。例如,如果有人在这个系统中编辑产品 ID 1234,我的服务器将收到一条警报,说产品 1234 已更改。然后我向他们 API 请求获取产品 1234 的最新数据并将其保存到我的系统中。

我正在构建此进程以异步工作。也就是说,每次我收到 webhook 时,我都会将详细信息保存到记录资源 ID 的数据库 table。然后我有一个 WebhookQueue class 包含一个 run() 方法,它处理所有排队的请求并更新适当的产品。这是来自 WebhookQueue class:

的代码
public static function run()
{
        //get request data
        $requests = WebhookRequest::select(
                        'webhook_type',
                        'object_ext_id',
                        'object_ext_type_id',
                        \DB::raw('max(created_at) as created_at')
                )
                ->groupBy(['webhook_type', 'object_ext_id', 'object_ext_type_id'])
                ->get();

        foreach ($requests as $request) {
                // Get the model for each request.
                // Make sure the model is not currently syncing.
                // Sync the model.
                // Delete all webhook request of the same type that were created before created_at on the request
                if ($request->webhook_type == 'product') {
                        $model = Product::where([
                                        'ext_id'=> $request->object_ext_id,
                                        'ext_type_id'=> $request->object_ext_type_id
                                ])->firstOrFail();

                        if (!$model->is_syncing) {
                                $model->syncWithExternal();

                                WebhookRequest::where([
                                        'webhook_type'=>$request->webhook_type,
                                        'object_ext_id'=>$request->object_ext_id,
                                        'object_ext_type_id'=>$request->object_ext_type_id,
                                ])
                                ->where('created_at', '<=', $request->created_at)
                                ->delete();
                        }
                }
        }
}

我还创建了一个命令,它只执行一行代码来处理队列。这个命令是php artisan run-webhook-queue.

我的计划是每 5 秒通过一个 cron 作业 运行 这个命令,但我刚刚了解到 cron 作业不能比分钟更细粒度地安排。

我怎样才能让这个命令每 5 秒发送一次 运行,或者有其他方法可以处理这种情况吗?我对 Laravel 队列一无所知,但似乎我应该使用它。

Laravel Worker Queues 可以很好地处理这个问题,并允许您每 5 秒执行一次 运行 命令。如果您使用 Forge,设置几乎不需要任何工作。

这是使用 Forge 的指南:https://mattstauffer.co/blog/laravel-forge-adding-a-queue-worker-with-beanstalkd

如果您不使用 Forge,这里有一个指南:http://fideloper.com/ubuntu-beanstalkd-and-laravel4