如何查看MYSQL复制中的延迟?
一般来说我们看Second_Behind_Master的值就可以判断了,但是并不准确。这篇文字详细地阐述了如何正确的查看复制中的延迟问题。
首先我们需要明确Time值的意义。
mysql > show full processlist\G
*************************** 1. row ***************************
Id: 6
User: system user
Host:
db: NULL
Command: Connect
Time: 22005006
State: Waiting for master to send event
Info: NULL
*************************** 2. row ***************************
Id: 7
User: system user
Host:
db: NULL
Command: Connect
Time: 3293
State: Updating
Info: UPDATE ** SET ** WHERE **
在replication 进程中,Time 可能有以下几种情况:
对于SQL线程:
1.当前没有活跃SQL时,Time的值就是SQL线程的空闲时间。此时Second_behind_master的值为0
2.当前有活跃SQL时,Time的值是SQL线程当前执行的relay log中的timestamp与IO线程中最新的timestamp的差值,也就是Second_Behind_Master 的值。
对于IO线程:
Time表示的是IO线程从启动到现在的总时长。
那么我们到底应该如何正确判断Slave的延迟情况呢?
1.首先看Relay_Master_Log_File和Master_Log_File是否有差异;
2.如果没有差异,说明延迟没有跨日志文件。然后我们再看Exec_Master_Log_Pos和Read_Master_Log_Pos的差异,对比SQL线程比IO线程慢多少个binlog events;
3.如果Relay_Master_Log_File和Master_Log_File不一样,那说明延迟跨日志文件,需要从Master节点获取当前binlog和Slave上执行的binglog 的差距。
下面演示步骤:
1.无活跃SQL
Master节点:
mysql> show binary logs;
+------------------+-----------+
| Log_name | File_size |
+------------------+-----------+
| mysql-bin.000001 | 100596 |
| mysql-bin.000002 | 2265 |
| mysql-bin.000003 | 177 |
| mysql-bin.000004 | 154 |
+------------------+-----------+
4 rows in set (0.00 sec)
Slave节点:
mysql> show slave status\G
*************************** 1. row ***************************
Master_Log_File: mysql-bin.000004
Read_Master_Log_Pos: 154
Relay_Log_File: centos-relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.000004
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Exec_Master_Log_Pos: 154
Seconds_Behind_Master: 0
可以看到此时
Slave_SQL_Running_State: Slave has read all relay log;
Seconds_Behind_Master: 0
说明当前SQL线程空闲,无延迟。
2.存在活跃SQL:
在 MASTER 上执行 SHOW BINARY LOGS 的结果是:
+------------------+--------------+
| Log_name | File_size |
+------------------+--------------+
| mysql-bin.000009 | 1073742063 |
| mysql-bin.000010 | 107374193 |
+------------------+--------------+
而在 SLAVE 上执行 SHOW SLAVE STATUS\G 的结果是:
Master_Log_File: mysql-bin.000009
Read_Master_Log_Pos: 668711237
Relay_Master_Log_File: mysql-bin.000009
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
***
Exec_Master_Log_Pos: 654409041
***
Seconds_Behind_Master: 3296
***
这时候, SLAVE 实际的延迟应该是:
mysql-bin.000009 这个 binlog 中的 binlog position 1073742063 和 SLAVE上读取到的 binlog position 之间的差异延迟:
1073742063 - 654409041 = 419333022 个 binlog events
并且还要加上 mysql-bin.000010 这个 binlog 已经产生的 107374193 个 binlog event,共107374193 + 419333022 = 526707215 个 binlog event