背景
之前搭建了主从,但没有设置读写分离,从库也能写数据。于是想测试下在从库写数据会导致同步怎么样。 结果发现,slave_sql_running为no,slava_IO_running仍然为yes.
原因
由于从库写数据,导致主从数据不一致,如果在主库写入和从库同样的数据,会导致sql线程终止,查看mysql错误日志如下:
2020-08-01T10:58:19.623077Z 135 [ERROR] Slave SQL for channel '': Could not execute Write_rows event on table shy_dep.zp_test; , Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event's master log mysql-bin.000001, end_log_pos 882496, Error_code: 10622020-08-01T10:58:19.623101Z 135 [Warning] Slave: Error_code: 10622020-08-01T10:58:19.623110Z 135 [ERROR] Error running query, slave SQL thread aborted. Fix the problem, and restart the slave SQL thread with "SLAVE START". We stopped at log 'mysql-bin.000001' position 882218
解决方法一
在从库停掉slave同步,执行 stop slave;
主库执行 SHOW MASTER STATUS,记录下File和Position的值
从库根据主库的position位置重新连接进行同步
CHANGE MASTER TO master_host = '192.168.164.84',MASTER_PORT = 3306,master_user = 'root',master_password = 'root',master_log_file = 'mysql-bin.000001',master_log_pos = 902262;#这里记录master最新的position
从库启动同步, start slave;
通过以上步骤,可以实现主从重新开始同步。
PS: 这里在重新启动从库同步时,假设主库没有进行写操作。因为如果进行了写操作,则刚才记录的主库position位置可能会变。
所以一般需要把主库临时加锁不让写。
解决方法二
在从库执行以下命令:
stop slave;set GLOBAL SQL_SLAVE_SKIP_COUNTER=1;start slave;SHOW SLAVE STATUS.........