我正在编写一个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回滚事务?
EntityManager
的情况下,它将进入关闭状态并抛出一个ORMException
,指示实体管理器已关闭,并在第二次尝试时引发异常。Doctrine版本2.4.*。 - Mantas\Doctrine\DBAL\Exception\RetryableException
异常,可以捕获Doctrine\DBAL\Exception\DeadlockException
和Doctrine\DBAL\Exception\LockWaitTimeoutException
。文档在此我建议根据您的版本捕获这些异常,而不是通用异常。 - Valentin Silvestre