gpt4 book ai didi

php - 如果 Doctrine 中不存在,并发请求试图创建相同的实体

转载 作者:行者123 更新时间:2023-11-29 00:01:22 26 4
gpt4 key购买 nike

我有一个看起来像这样的函数:

function findByAndCreateIfNotExists($criteria){

$entity = $this->findBy(['criteria'=>$criteria]);

// this is the problem area, if request 1 is still creating the entity, request 2 won't find it yet.

if (! $entity) {
$entity = $this->createEntity($criteria);
}

return $entity;
}

这个函数被各种请求使用,我发现并发请求有时会尝试创建相同的实体,抛出 DBALException 提示唯一键的重复条目。

我考虑过这里提到的 LOCK TABLES: How to lock a whole table in symfony2 with doctrine2?

但鉴于在 Doctrine 中没有执行此操作的功能,我猜这不是首选方法。我的问题是,如何防止并发请求尝试创建相同的实体并始终返回正确的实体?

最佳答案

作为想法创建自己的锁定系统:

类似于:

function findByAndCreateIfNotExists($criteria){

$entity = $this->findBy(['criteria'=>$criteria]);

// this is the problem area, if request 1 is still creating the entity, request 2 won't find it yet.
$lockPath ='/tmp/'.md5($criteria).'.lock';

if (! $entity && !file_exists($lockPath)) {
$fh = fopen($lockPath, 'w') or die("Can't create file");
$entity = $this->createEntity($criteria);
unlink(($lockPath);
}

return $entity;
}

关于php - 如果 Doctrine 中不存在,并发请求试图创建相同的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29644717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com