原理
MYSQL的主从同步是在MYSQL的主从复制(master-slave Replication)的基础上实现的。其实现方式:
- 设置主服务器的binlog使其在开启状态下;
- Slave mysql 通过一个I/O线程来获取主服务器的binlog文件,然后传输到Slave mysql的中继日志中
- Slave mysql 的SQL线程读取中继日志中的binlog,还原到Slave mysql数据库中。
步骤
准备
主从数据库版本一致
库中数据一致
Master服务器配置
修改配置文件my.cnf
#日志名
log-bin = mysql-bin
#主数据库ID
server-id = 1
重启MYSQL服务,创建用于主从同步的用户
mysql> grant replicate slave on *.* to 'user'@'%' identified by '123456';
mysql> flush privileges;
查看主数据库状态
show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000012 | 327 | crm | |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
锁定主数据库,再不要进行操作
flush tables with read lock
减除表的锁
unlock tables;
slave 数据配置
修改my.cnf配置文件
server-id = 2
执行同步命令
mysql> change master to
-> master_host = '192.168.1.1',
-> master_user = 'mysql',
-> master_password = 'mysql',
-> master_log_file = 'mysql-bin.000012',
-> mastet_log_pos = 327;
#开启同步命令
start slave;
查看状态
show slave status \G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 60.205.105.99
Master_User: rep
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000012
Read_Master_Log_Pos: 327
Relay_Log_File: mysqld-relay-bin.000027
Relay_Log_Pos: 252
Relay_Master_Log_File: mysql-bin.000012
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: 327
Relay_Log_Space: 554
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: 0
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: 1
1 row in set (0.00 sec)
如果:
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
这两项都为Yes,则为正常状态,至此全部配置完成。
其他配置
master端
#不同步哪些数据库
binlog-ignore-db = mysql
binlog-ignore-db = test
#只同步哪些库
binlog-do-db = crm
#日志保留时间
expire_logs_days = 10
#控制binlog的写入频率,每执行多少次写入事务一次
#比较耗费资源,但可以减少mysql崩溃造成的损失。
sync_binlog = 5
#日志格式
binlog_format = mixed
slave端
#连接断开时,重新连接的超时时间
mysql> change master to master_connect_retry = 50
问题处理
Slave_SQL_Running: No
遇到这种情况有可能是事务回滚造成的,可以这样解决
mysql> stop salve;
mysql> set GLOBAL SQL_SLAVE_SKIP_COUNTER=1
mysql> start salve;
相关文章:MariaDB(mysql)之主从同步
网友评论