php – 如何使用Doctrine在死锁后重试事务?
发布时间:2020-12-13 14:15:25 所属栏目:PHP教程 来源:网络整理
导读:我正在编写一个 PHP函数,它将大量数据存储/更新到表中,这可能会导致死锁.我试图调查如何使用Doctrine重试失败的事务,但遗憾的是无法在线查找任何信息.我最终写了下面的代码 $retry = 0; $done = false; while (!$done and $retry 3) { try { $this-entityMan
我正在编写一个
PHP函数,它将大量数据存储/更新到表中,这可能会导致死锁.我试图调查如何使用Doctrine重试失败的事务,但遗憾的是无法在线查找任何信息.我最终写了下面的代码
$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回滚交易呢?
死锁返回错误1213,您应该在客户端处理该错误
请注意,死锁和锁定等待是不同的事情.陷入僵局,没有“失败”的交易:他们都有罪.无法保证哪一个将被回滚. 您必须使用回滚,您的样式代码将插入重复.例如你应该: $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++; } } 希望这有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |