Php 如何在高并发性中插入绝对数量的数据。关于间隙锁升级插入意图锁
期望: 有这样一个表数据: 身份证号码 1 | 10 | 10 2 | 10 | 15 现在我想插入id=3 number=20(添加id=2的数据) 在PHP中,我的代码如下所示。当执行某些命令时(当间隙锁升级插入意图时),将出现此错误。但是没有发生错误,程序甚至没有停止 在下面重复此错误: trx1和2 or(php中的文件1和2)在两个终端查询中执行Php 如何在高并发性中插入绝对数量的数据。关于间隙锁升级插入意图锁,php,laravel,pdo,mysql-5.7,Php,Laravel,Pdo,Mysql 5.7,期望: 有这样一个表数据: 身份证号码 1 | 10 | 10 2 | 10 | 15 现在我想插入id=3 number=20(添加id=2的数据) 在PHP中,我的代码如下所示。当执行某些命令时(当间隙锁升级插入意图时),将出现此错误。但是没有发生错误,程序甚至没有停止 在下面重复此错误: trx1和2 or(php中的文件1和2)在两个终端查询中执行 //prepared: CREATE TABLE `test_lock` ( `id` int(11) NOT NULL AUTO_IN
//prepared:
CREATE TABLE `test_lock` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aid` int(11) NOT NULL,
`otherinfo` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `aid` (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
insert into `test_lock` (`aid`) values(10);
##trx1 and trx2
begin;
##trx1
select max(id) from `test_lock` where (`aid` = 10) limit 1 for update;
##trx2(have blocked)
select max(id) from `test_lock` where (`aid` = 10) limit 1 for update;
##trx1
insert into `test_lock` (`aid`) values(10);
##then trx2 will gave a deadlock error and look that error
show engine innodb status\G;
使用PHP进行测试(我使用Laravel5.6命令):
执行file1。然后打开另一个终端执行file2,就可以得到这个错误
我在mysql bug center上报告了此错误:
但他们告诉我这不是虫子。这只是死锁的典型场景。
但只要改变睡眠位置(在文件1中)就可以按预期工作。
现在我该怎么办呢?评论不是为了进一步讨论;这段对话已经结束。
//file1:
$aid = 10;
DB::beginTransaction();
$result = DB::table('test_lock')->where('aid', $aid)->orderByDesc('id')->lockForUpdate()->first();
var_dump($result);
echo "after get:" . date('Y-m-d H:m:s.u'). "\r\n";
sleep(10); // wrong
DB::table('test_lock')->insert(
['aid' => $aid]
);
echo "after insert:" . date('Y-m-d H:m:s.u'). "\r\n";
//sleep(10); // correctly and file2 is correct result
DB::commit();
//file2
$aid = 10;
DB::beginTransaction();
$pdo = DB::connection()->getPdo();
$result = DB::table('test_lock')->where('aid', $aid)->orderByDesc('id')->lockForUpdate()->first();
var_dump($result); //NULL
echo "after get:" . date('Y-m-d H:m:s.u'). "\r\n";
var_dump($pdo->errorCode()); // 00000
$ret = DB::table('test_lock')->insert(
['aid' => $aid]
);
echo "after insert:" . date('Y-m-d H:m:s.u'). "\r\n";
DB::commit();