MySQL死锁是指两个或多个事务在同一资源上相互等待的情况,若无外力作用,它们都将无法推进下去。死锁是并发事务处理中的一个常见问题,通常发生在多个事务互相持有对方需要的资源时。
死锁常见于高并发、多用户、多表操作的场景,如电商平台的订单处理系统、银行转账系统等。
当MySQL检测到死锁时,它会自动选择一个事务进行回滚,并在错误日志中记录相关信息。你可以通过以下方式查看死锁的SQL:
/var/log/mysql/error.log
(具体路径可能因安装方式和操作系统而异)。在日志中搜索“Deadlock”关键字,可以找到相关的死锁信息。SHOW ENGINE INNODB STATUS
命令:这个命令可以显示InnoDB存储引擎的当前状态,包括最近的死锁信息。执行该命令后,在输出结果中找到“LATEST DETECTED DEADLOCK”部分,即可查看详细的死锁信息。以下是一个简单的示例,展示如何使用SHOW ENGINE INNODB STATUS
命令查看死锁信息:
SHOW ENGINE INNODB STATUS;
执行上述命令后,你将看到类似以下的输出(只展示关键部分):
------------------------
LATEST DETECTED DEADLOCK
------------------------
2023-04-01 12:34:56 0x7f8d9a0c1700
*** (1) TRANSACTION:
TRANSACTION 12345678, ACTIVE 0.5 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 376 bytes, 1 row lock(s)
MySQL thread id 123, OS thread handle 0x7f8d9a0c1700, query id 1234 localhost root updating
UPDATE table_name SET column = 'value' WHERE id = 1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 123 page no 4 n bits 72 index `index_name` of table `database_name`.`table_name` trx id 12345678 lock_mode X waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
...
*** (2) TRANSACTION:
TRANSACTION 12345679, ACTIVE 0.5 sec updating or deleting
mysql tables in use 1, locked 1
2 lock struct(s), heap size 376 bytes, 1 row lock(s)
MySQL thread id 124, OS thread handle 0x7f8d9a0c1701, query id 1235 localhost root updating
UPDATE table_name SET column = 'value' WHERE id = 2
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 123 page no 4 n bits 72 index `index_name` of table `database_name`.`table_name` trx id 12345679 lock_mode X locks rec but not gap
Record lock, heap no 1 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
...
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 123 page no 4 n bits 72 index `index_name` of table `database_name`.`table_name` trx id 12345679 lock_mode X waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
...
领取专属 10元无门槛券
手把手带您无忧上云