簡體   English   中英

Symfony2:如何將INSERT DELAYED與doctrine一起使用或創建非阻塞數據庫操作?

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

出於性能原因,我想使用mysql的INSERT DELAYED查詢來持久保存日志對象。

你有什么想法可以使用學說來執行嗎?

為什么你可能不應該使用INSERT DELAYED:

從MySQL 5.6.6開始,不推薦使用INSERT DELAYED,並將在以后的版本中刪除。 請改用INSERT(不帶DELAYED)。

官方文件

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();
    }
}

然后將其定義為服務並注入對象管理器:

# 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" ]

最后,您可以從控制器或某個服務內部向記錄器添加數據, 然后在響應發送以非阻塞方式激活並執行數據庫操作。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM