gpt4 book ai didi

php - Symfony2 : How to use INSERT DELAYED with doctrine or create a non-blocking database operation?

转载 作者:可可西里 更新时间:2023-11-01 00:44:53 28 4
gpt4 key购买 nike

出于性能原因,我想使用 mysql 的 INSERT DELAYED 查询来保留一个日志对象。

您是否知道如何使用 Doctrine 来执行此操作?

最佳答案

为什么你可能不应该使用 INSERT DELAYED:

As of MySQL 5.6.6, INSERT DELAYED is deprecated, and will be removed in a future release. Use INSERT (without DELAYED) instead.

( official documentation )

symfony2 解决方案:

使用 symfony2,您可以通过为 kernel.terminate 事件创建监听器/订阅器并在其中执行它来执行非阻塞数据库操作。

发送响应会触发此事件。例如,生产环境中的 monolog 正在使用它。

先创建一个监听类:

namespace Acme\Your;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpKernel\Event\KernelEvent;

class LongOperationLogger
{
protected $om;
protected $data;

public function __construct(ObjectManager $om)
{
$this->om = $om;
}

public function setData($data)
{
$this->data = $data;
}

public function onKernelTerminate(KernelEvent $event)
{
// don't do anything if there is not data
if ( null !== $this->data ) {
return;
}

$logEntry = new LogEntry('I will not block the response.', $this->data);

$this->om->persist($logEntry);
$this->om->flush();
}
}

然后将其定义为服务并注入(inject)您的对象管理器:

# app/config/config.yml

services:
long_operation.logger:
class: Acme\Your\LongOperationLogger
tags:
- { name: kernel.event_listener, event: kernel.terminate }
arguments: [ "@doctrine.orm.entity_manager" ]

最后,您可以从 Controller 或某些服务内部向记录器添加数据,这些服务会在发送响应后以非阻塞方式激活和执行数据库操作。

public function someAction()
{
// some condition
// if (...) {
// ...
// }

$this->get('long_operation.logger')->setData($whatever)
}

关于php - Symfony2 : How to use INSERT DELAYED with doctrine or create a non-blocking database operation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21993794/

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