gpt4 book ai didi

Laravel 5.4 通过异步队列保存模型

转载 作者:行者123 更新时间:2023-12-02 11:59:38 24 4
gpt4 key购买 nike

因此,我尝试优化我的网站,在每个页面加载和退出时,我都会保存一个指标(页面停留时间、IP 地址等)用于分析。然而,这些是我的服务器上相当大的瓶颈。当查看运行整个函数所需的时间时,我需要大约 1-2 毫秒,然后保存到数据库大约需要 100-200 毫秒。所以我的目标是运行我的函数,然后分派(dispatch)一个新作业,这将实际保存指标。这样,我的模型的所有保存都可以卸载到队列中。以下是我的工作副本

class SaveMetric implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Execute the job.
*
* @return void
*/
public function handle(Metrics $metric)
{
//
$metric->save();
}
}

然后在我的 Controller 函数中获取我需要的所有值后运行此

dispatch(new SaveMetric($newMetric));

这似乎可以运行,但似乎没有做任何事情。我错过了什么吗? (编辑)这做了~一些事情~它只是将一条记录保存到数据库,所有字段中都为空,就好像我创建了一个没有任何值的新指标一样。

  • 是否需要将队列传递到作业调度中?
  • 我是否需要运行守护程序或类似的程序来实际处理队列中的内容?

我使用 artisan make:job 命令创建了作业

最佳答案

你已经很接近了。

class SaveMetric implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

protected $metric;

/**
* Create a new job instance.
*
* @param Metrics $metric
*/
public function __construct(Metrics $metric)
{
$this->metric = $metric;
}

/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->metric->save();
}
}

根据the docs :

In this example, note that we were able to pass an Eloquent model directly into the queued job's constructor. Because of the SerializesModels trait that the job is using, Eloquent models will be gracefully serialized and unserialized when the job is processing. If your queued job accepts an Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database.

关于Laravel 5.4 通过异步队列保存模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com