Mysql主从复制操作
一、主从同步的环境
我们假定有A、B两台服务器,B作为A的一个远程容灾备份机,A上的Mysql数据要实时同步到B上。
假设我们的安装环境为:
Master主服务器A的IP地址:172.30.25.244
Slave 从服务器B的IP地址:172.30.25.245
A和B的Mysql版本一致或者A的版本比B要高(杜绝B的版本比A高)
红色字体:需要视实际情况进行修改
二、修改配置文件
1、修改A服务器的配置文件
vi /etc/my.cnf
找到server-id这行,修改server-id并在此行位置后面添加下面内容:
server-id = 1
log-bin=mysql-bin
relay_log = mysql-relay-bin
relay_log_index = mysql-relay-bin.index
binlog-do-db=test_xyp ##需要复制的数据库
2、修改B服务器的配置文件
vi /etc/my.cnf
找到server-id这行,修改server-id并在此行位置后面添加下面内容:
server-id = 2
replicate-do-db=test_xyp ##需要复制的数据库
修改完后重启A和B的Mysql:
service mysql restart;
三、对A进行Mysql操作
1、在A上为B建立一个用户
登录Mysql,并且为从服务器建立一个同步用户。
规格为:grant replication slave on *.* to '用户名'@'Slave主机' identified by '密码';
grant replication slave on *.* to 'appstore_appli'@'172.30.25.245' identified by 'coship';
flush privileges;
2、停止A服务,并导出数据
3、查看A的同步日志偏移信息
查看Master的同步日志偏移信息:
mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000164 | 233 | test_xyp | |
+------------------+----------+--------------+------------------+
将mysql-bin.000164和233记录下来(后面有用到):
四、在B上进行Mysql操作
1、将A导出的数据导入到B中
2、指定同步日志的偏移
登录Mysql:
STOP SLAVE;
CHANGE MASTER TO MASTER_HOST='172.30.25.244',MASTER_USER='appstore_appli',MASTER_PASSWORD='coship', MASTER_LOG_FILE='mysql-bin.000164', MASTER_LOG_POS=233;
START SLAVE;
查看同步状态,看看和A的是否一致:
mysql> show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 172.30.25.244
Master_User: appstore_appli
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000164
Read_Master_Log_Pos: 233
Relay_Log_File: coship245-relay-bin.000002
Relay_Log_Pos: 252
Relay_Master_Log_File: mysql-bin.000166
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB: test_xyp
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: 233
Relay_Log_Space: 412
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
五、进行数据同步测试,看是否OK