使用学说僵局后如何重试交易? 我正在编写PHP功能,该功能将大量数据存储到表中,这可能会导致僵局。我尝试调查如何通过学说重试失败的交易,但可悲的是...

问题描述 投票:0回答:3
这种方法有可能在数据库中插入重复项吗?如果是这样,我该如何强制教义回滚交易?

僵局返回错误1213您应该在客户端进行处理

注意,僵局和锁定等待是不同的事情。在僵局中,没有“失败”的交易:他们都是有罪的。不能保证将要回去哪一个。 您必须使用

rollback
php mysql database doctrine-orm deadlock
3个回答
19
投票

$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++; } }

this帮助

这是我如何处理与SF2.7和学说2.4.7:

重试交易失败交易的方式:

use Doctrine\Bundle\DoctrineBundle\Registry; use Doctrine\ORM\EntityManager; class Foo { /** * @var Registry */ protected $doctrine; public function __construct(Registry $registry) { $this->doctrine = $registry; } protected function doSomething($entity, $attempt) { $em = $this->getEntityManager(); $conn = $em->getConnection(); try{ $conn->beginTransaction(); $entity->setBar("baz"); $em->flush(); $conn->commit(); } catch(\PDOException $e){ $conn->rollBack(); $attempt++; if($attempt <= 3){ $this->doSomething($repayment, $attempt); } } } /** * @return EntityManager */ protected function getEntityManager() { /** @var EntityManager $em */ $em = $this->doctrine->getManager(); if(!$em->isOpen()){ $this->doctrine->resetManager(); $em = $this->doctrine->getManager(); } return $em; } }
    

重新交易片段

3
投票
获得连接并没有混乱。

循环正确处理

代码

2
投票
关于学说交易的更多信息可以在

Https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/reference/transactions/transactions-and-concurrency.html

  • 如何获得连接:
  • simply注入学说的
  • EntityManager

Interface

)或
Connection
通过构造函数 Connection

public function __construct(Connection $connection) { $this->connection = $connection; }

或EntityManager

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}
获得连接为
$this->entityManager->getConnection()

如果您不使用ORM,然后使用它会自动管理僵局的情况。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.