我正在使用一个系统,该系统中的资源随时都可以向我发送webhook。webhook包含被更新的资源的id。例如,如果有人在这个系统中编辑了产品ID 1234,我的服务器将收到一条警告,说产品1234已经更改。然后我向他们的API请求获取产品1234的最新数据并将其保存到我的系统。
我正在构建此流程以异步工作。这意味着,每次我接收到一个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队列,但似乎我应该使用它。
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