我正在使用一个系统,该系统会在系统中的某个资源发生更改时随时向我发送webhook。 webhook包含已更新的资源的ID。例如,如果有人在此系统中编辑产品ID 1234,我的服务器将收到一条警报,称产品1234已更改。然后,我向他们的API发出请求,以获取产品1234的最新数据并将其保存到我的系统中。Laravel每5秒运行一次工匠命令
我正在建立这个过程异步工作。意思是,每当我收到webhook时,我都会将详细信息保存到记录资源ID的数据库表中。然后,我有一个WebhookQueue
类,其中包含run()
方法,该方法处理所有排队的请求并更新相应的产品。下面是来自WebhookQueue
类的代码:
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队列一无所知,但似乎我应该使用它。
如果你正在运行每5秒那岂不是更有意义只是为了处理请求当你收到警报? – cmorrissey
有时,外部系统将发送多个webhook以进行相同的更改。在这些情况下,我会收到一个又一个请求,但实际上只应该同步一次。这样做更有意义,因为这两个webhook可以组合在一起。此外,5秒的时间间隔可能会改变。 – flyingL123