大家都知道MySQL中查看主备延迟最准确的方式是定时往主机一张延时监控表插入当前时间,再对比主备机这张表的时间差,自带的show slave status\G
是不准确的,譬如有大事务时Seconds_Behind_Master会瞬间极大然后继续慢慢增加,最后等大事务在从机执行完毕又瞬间恢复为0。
但今天发现一台从机的Seconds_Behind_Master瞬间极大达到几万秒然后又很快恢复到0秒,这肯定不是大事务导致的,那是什么呢?答案是:长时间未提交的小事务
下面做个试验:
主机执行完语句后不立即commit
root@test04:51:56>begin;
Query OK, 0 rows affected (0.07 sec)
root@test04:52:01>update test set a='12346fdsvfdsvda' where id < 1000000;
Query OK, 737882 rows affected (7.11 sec)
等待3分钟后commit
root@test04:55:09>commit;
Query OK, 0 rows affected (0.08 sec)
在备机上看,Seconds_Behind_Master瞬间达到187秒
root@(none)04:51:51>show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: XXXX
Master_User: XXXX
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000104
Read_Master_Log_Pos: 385489047
Relay_Log_File: mysql-relay-bin.000017
Relay_Log_Pos: 355843515
Relay_Master_Log_File: mysql-bin.000104
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 355843302
Relay_Log_Space: 385489514
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 187
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 22633068
Master_UUID: 40e53a43-71db-11e7-bea0-38bc019cd0d3
Master_Info_File: mysql.slave_master_info
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Reading event from the relay log
Master_Retry_Count: 86400
Master_Bind:
Last_IO_Error_Timestamp:
Last_SQL_Error_Timestamp:
Master_SSL_Crl:
Master_SSL_Crlpath:
Retrieved_Gtid_Set:
Executed_Gtid_Set: 40e53a43-71db-11e7-bea0-38bc019cd0d3:1-29:116-123:127-139
Auto_Position: 0
Replicate_Rewrite_DB:
Channel_Name:
Master_TLS_Version:
1 row in set (0.00 sec)
因为上面在主机update执行了7s,所以备机Seconds_Behind_Master从187秒缓慢增长到204秒(187+7)然后瞬间恢复为0,假如是一个很快执行完的小update语句,则备机表现就是Seconds_Behind_Master瞬间增长到187秒又极快恢复至0秒了~