主义悲观锁

Doctrine Pessimistic Lock

场景:

我正在 Symfony2 中实现一个应用程序 运行 每五分钟执行一次命令(cronjob),它通过 MySql table 并且在每条记录中,首先读取 json_array 字段,进行一系列的计算,最后将新数据保存在同一字段的数组中。此外,还有一个 Web 应用程序,用户可以在其中编辑和保存此数据 table

为了避免并发,如果命令访问一条记录,我会创建一个悲观锁,这样,如果用户在那一刻更改数据,则必须等到事务结束并完成用户数据已保存。

但是当用户保存数据时,随机出现一个错误,用户数据没有保存,网络应用程序显示以前的数据,这告诉我锁定没有成功。

symfony2 命令中我设置悲观锁的代码:

    foreach ($this->cisOfferMetaData as $oldCisOfferMeta) {
        // calculate budget used for each timeframe case and save it

        // begin transaction and Lock cisOfferMEta Entity
        $this->em->getConnection()->beginTransaction();
        try {
            $cisOfferMeta = $this->em->getRepository('CroboCisBundle:CisOfferMeta')->find(
                $oldCisOfferMeta->getId(),
                LockMode::PESSIMISTIC_READ
            );

            $budget = $cisOfferMeta->getBudgetOffer();

            foreach (
                generator(CisOfferMeta::getTypesArray(), CisOfferMeta::getTimeframesArray())
                as $type => $timeframe
            ) {
                if (isset($budget[$type][$timeframe]['goal'])) {
                    // if type=budget we need revenue value, if type=conversion, conversions value
                    $budget[$type][$timeframe]['used'] =
                        ($type === 'conversion')
                            ? intval($allTimeframes[$key]['conversions'][$timeframe])
                            : round($allTimeframes[$key]['revenue'][$timeframe], 2);

                    $budget[$type][$timeframe]['percent_reached'] =
                        ($budget[$type][$timeframe]['used'] == 0.0)
                            ? 0.0
                            : round(
                            $budget[$type][$timeframe]['used'] / intval($budget[$type][$timeframe]['goal']) * 100,
                            2
                        );
                }
            }

            $budget['current_conversions'] = $allTimeframes[$key]['conversions'];
            $budget['current_revenue'] = $allTimeframes[$key]['revenue'];

            $cisOfferMeta->setBudgetOffer($budget);

            $this->em->flush($cisOfferMeta);
            $this->em->getConnection()->commit();
        } catch (PessimisticLockException $e) {
            $this->em->getConnection()->rollback();
            throw $e;
        }

    }

我是不是做错了什么?我想由于事务在提交更改之前开始,如果用户尝试读取或更新数据,则必须等到锁定从被阻止的实体中释放。

看Doctrine文档不清楚是否应该在实体中添加版本控制

最后这段代码正常工作并产生了悲观锁,问题出在一个侦听器中,它在这个锁之前读取数据,然后在锁释放后没有更改地刷新。