同时添加和更新记录时发生死锁错误

时间:2018-05-04 07:03:47

标签: php mysql deadlock

我们目前正在开发一个包含许多交易的项目。用户在队列表中添加顺序,另一个脚本处理事务。当添加事务和队列引擎同时工作时,会发生死锁错误。

排队表

CREATE TABLE `order_queue` (
    `OrderId` BIGINT(20) UNSIGNED NOT NULL,
    `State` TINYINT(3) UNSIGNED NOT NULL COMMENT '1=adding, 11=proccessing, 2=complete',
    `EngineId` SMALLINT(5) UNSIGNED NOT NULL,
    `AddTime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`OrderId`),
    INDEX `State` (`State`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

添加交易

$db->beginTransaction();
$db->exec("INSERT INTO order_queue (OrderId, State, EngineId) VALUES ({$OrderId}, 1, 0)");
$db->commit();

最后我们有三个队列引擎来获取交易并发送另一个系统

$db->query("UPDATE order_queue SET State=11,EngineId={$EngineId} WHERE State=1 LIMIT 1");

$qOrder = $db->query("SELECT * FROM order_queue 
            WHERE State=11 AND EngineId={$EngineId}")->fetch();

echo $qOrder->OrderId;
//send the order to other systems
$db->exec("UPDATE order_queue SET State=2 WHERE OrderId={$qOrder->OrderId}");

如果此脚本同时工作,则发生最受欢迎的错误

SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

我尝试了一些方法,首先检查AddTime,然后在State行之后更改$db->commit();等,但问题没有解决。

如果你是我,你会怎么做?哪种方法最好?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用"锁定共享模式"如下

$db->query("UPDATE order_queue SET State=11,EngineId={$EngineId} WHERE State=1 LIMIT 1");

$qOrder = $db->query("SELECT * FROM order_queue 
            WHERE State=11 AND EngineId={$EngineId} lock in share mode")->fetch();

echo $qOrder->OrderId;
//send the order to other systems
$db->exec("UPDATE order_queue SET State=2 WHERE OrderId={$qOrder->OrderId}");