MySQL的死锁是指两个或多个事务在同一资源上相互等待的情况,导致事务无法继续执行。MySQL通过日志记录死锁事件,便于排查和分析问题。
MySQL的死锁日志主要记录了以下类型的信息:
my.cnf
或my.ini
)中添加以下配置:my.cnf
或my.ini
)中添加以下配置:hostname-deadlock.log
。可以通过以下命令查看:hostname-deadlock.log
。可以通过以下命令查看:假设你有一个简单的表结构:
CREATE TABLE `accounts` (
`id` INT PRIMARY KEY,
`balance` DECIMAL(10, 2)
);
两个事务分别执行以下操作:
-- 事务1
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- 事务2
START TRANSACTION;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
如果这两个事务同时执行,可能会导致死锁。查看死锁日志可以看到类似以下的信息:
------------------------
LATEST DETECTED DEADLOCK
------------------------
2023-04-01 12:34:56 0x7f9b8c0b4700
*** (1) TRANSACTION:
TRANSACTION 123456, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 376, 1 row lock(s)
MySQL thread id 1234, OS thread handle 0x7f9b8c0b4700, query id 1234 localhost user updating
UPDATE accounts SET balance = balance - 100 WHERE id = 1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 3 n bits 72 index `PRIMARY` of table `test`.`accounts` trx id 123456 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 000000000014; asc ;;
2: len 7; hex 00000000000000000000; asc ;;
*** (2) TRANSACTION:
TRANSACTION 123457, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
2 lock struct(s), heap size 376, 1 row lock(s)
MySQL thread id 12345, OS thread handle 0x7f9b8c0b4701, query id 12345 localhost user updating
UPDATE accounts SET balance = balance + 100 WHERE id = 2
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 3 n bits 72 index `PRIMARY` of table `test`.`accounts` trx id 123457 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 000000000014; asc ;;
2: len 7; hex 00000000000000000000; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 3 n bits 72 index `PRIMARY` of table `test`.`accounts` trx id 123457 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000002; asc ;;
1: len 6; hex 000000000014; asc ;;
2: len 7; hex 00000000000000000000; asc ;;
*** WE ROLL BACK TRANSACTION (2)
通过以上步骤和方法,你可以有效地查看和分析MySQL的死锁日志,并采取相应的措施来解决死锁问题。
领取专属 10元无门槛券
手把手带您无忧上云