原文:https://www.52wiki.cn/Doc/Read/id/431.html
附:
mysql主从复制原理https://www.52wiki.cn/Doc/Read/id/430.html
mysql主主复制 https://www.52wiki.cn/Doc/Read/id/432.html
一. 环境准备
1.主从数据库版本最好一致
2.主从数据库内数据保持一致,若不一致,可将从库中所有数据删除,并将主库全部数据导入进去
主数据库:182.92.172.80
从数据库:123.57.44.85
二.操作
主数据库操作
1.开启binlog
[mysqld]
log-bin=mysql-bin #开启二进制日志
server-id=1 #设置server-id,和从不能一样
2.重启mysql,创建用于同步的用户账号
systemc restart mysql
登陆数据库
mysql -hlocalhost -uname -ppassword
创建用户并授权:用户:test密码:123456,ip修改为从的ip
CREATE USER 'test'@'123.57.44.85' IDENTIFIED BY '123456';
分配中权限
GRANT REPLICATION SLAVE ON *.* TO 'test'@'123.57.44.85';
flush privileges;
锁表,禁止写入,当前窗口不能退出,这时候开启另一个终端继续操作
flush table with read lock;
3.新窗口操作,查看master状态,记录二进制文件名(mysql-bin.000003)和位置(73):
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 73 | | |
+------------------+----------+--------------+------------------+
4.将当前数据导出
mysqldump -u root -p --all-databases > /root/alldb.sql
5.解锁查看binlog日志位置,如果没变证明锁定成功。从库将从这个binlog日志开始恢复
unlock table;
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 73 | | |
+------------------+----------+--------------+------------------+
从服务器操作
1.导入数据
mysql -uroot -p < alldb.sql
2.修改配置文件
vim /etc/my.cnf
[mysqld]server-id=2 #设置server-id,必须唯一
3.重启mysql,配置同步
需要主服务器主机名,登陆凭据,二进制文件的名称和位置
CHANGE MASTER TO MASTER_HOST='182.92.172.80', MASTER_USER='test', MASTER_PASSWORD='123456', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=73;
start slave;
4.查看slave状态:
show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 182.92.172.80
Master_User: rep1
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000013
Read_Master_Log_Pos: 11662
Relay_Log_File: mysqld-relay-bin.000022
Relay_Log_Pos: 11765
Relay_Master_Log_File: mysql-bin.000013
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
...
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
都是yes即可
网友评论