如何使用Doctrine在死锁后重试事务? [英] How to retry transaction after a deadlock using Doctrine?

查看:275
本文介绍了如何使用Doctrine在死锁后重试事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个PHP函数,用于将大量数据存储/更新到表中,并可能导致死锁。我试图调查如何重试与Doctrine失败的交易,但悲伤地没有找到任何信息在线。我最终写了以下代码:

I am writing a PHP function which store/updates large sets of data into a table and that may cause a deadlock. I tried investigating how to retry a failed transaction with Doctrine but sadly could not find any info online. I eventually wrote the following code

 $retry = 0;
 $done = false;
 while (!$done and $retry < 3) {
     try {

         $this->entityManager->flush();
         $done = true;

     } catch (\Exception $e) {
         sleep(1);

         $retry++;
     }
 }

 if ($retry == 3) {
     throw new Exception(
         "[Exception: MySQL Deadlock] Too many people accessing the server at the same time. Try again in few minutes"
     );
 }

我的问题:将在数据库中插入重复项?如果是的话,我如何强制Doctrine回滚事务?

My question: is there a chance this approach will insert duplicates in the database? if so, how can I force Doctrine to roll back the transactions?

推荐答案

死锁返回错误1213,客户端

A deadlock returns error 1213 which you should process on the client side

请注意,死锁和锁等待是不同的。在一个僵局中,没有失败的事务:他们都有罪。

Note that a deadlock and lock wait are different things. In a deadlock, there is no "failed" transaction: they are both guilty. There is no guarantee which one will be rolled back.

您必须使用 rollback ,您的样式代码才会插入重复的。例如您应该:

You must use rollback, your style code will insert duplicate. for example you should :

$retry = 0;

$done = false;


$this->entityManager->getConnection()->beginTransaction(); // suspend auto-commit

while (!$done and $retry < 3) {

    try {

        $this->entityManager->flush();

        $this->entityManager->getConnection()->commit(); // commit if succesfull

        $done = true;

    } catch (\Exception $e) {

        $this->entityManager->getConnection()->rollback(); // transaction marked for rollback only

        $retry++;

    }

}

这篇关于如何使用Doctrine在死锁后重试事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆