演示用两台全新MySql服务器:
mysql1:10.10.1.55 (主)
mysql2:10.10.1.56 (从)
配置主从,步骤如下:
STEP 1:在mysql1上创建复制账号 repl
CREATE USER 'repl'@'10.10.1.%' IDENTIFIED BY 'myRep8%Go';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl'@'10.10.1.%';
STEP 2:在mysql1上编辑 /etc/my.cnf 文件,增加两行
log_bin=mysql-bin
server_id=55
开启二进制日志和设置server_id(只能是数字,此处用IP地址后两位),然后重启mysqld,
用root账号登录进去,执行“SHOW MASTER STATUS”语句,检查输出是否与如下一致
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+----------
---------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
Executed_Gtid_Set |
+------------------+----------+--------------+------------------+----------
---------+
| mysql-bin.000001 | 154 | | |
|
+------------------+----------+--------------+------------------+----------
---------+
1 row in set (0.00 sec)
STEP 3:在mysql2上编辑 /etc/my.cnf 文件,增加以下配置,然后重启mysqld
log_bin=mysql-bin
server_id=56
relay_log=/var/lib/mysql/mysql-relay-bin
log_slave_updates=1
read_only=1
如果采用“主-主”结构,read_only为可选配置
STEP 4:登录mysql2数据库,执行以下语句,让mysql2连接到mysql1,并重放其二进制日志
CHANGE MASTER TO MASTER_HOST='10.10.1.55',
MASTER_USER='repl',MASTER_PASSWORD='myRep8%Go', MASTER_LOG_FILE='mysqlbin.000001', MASTER_LOG_POS=154;
执行成功后,再输入“SHOW SLAVE STATUS\G”检查配置是否正确,如下所示
mysql> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_State:
Master_Host: 10.10.1.55
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 4
Relay_Log_File: mysql-relay-bin.000001
Relay_Log_Pos: 4
Relay_Master_Log_File: mysql-bin.000001
Slave_IO_Running: No
Slave_SQL_Running: No
Slave_IO_State 为空,Slave_IO_Running 和 Slave_SQL_Running 均为 NO,表示复制并未运
行,
要启动复制还需运行命令“START SLAVE”
mysql> START SLAVE;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 10.10.1.55
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 623
Relay_Log_File: mysql-relay-bin.000001
Relay_Log_Pos: 836
Relay_Master_Log_File: mysql-bin.000001
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
后记:
如果对mysql1再做一遍和mysql2类似的配置,即可把mysql1设置为mysql2的从库,实现“主-
主”热备结构。通常来说一个高可用的读写分离数据库架构至少需要三台服务器:一台主,一台
热备主,一台只读。
删除主从配置命令
reset master: 删除所有的二进制日志,并重新创建一个新的二进制日志
reset slave all: 从slave删除主从复制关系的位置信息,并完全的清理复制连接参数信息
mysql 重启的话 要 重放其二进制日志
查看是否开启二进制日志
w variables like '%log_bin%';
CHANGE MASTER TO MASTER_HOST='192.168.237.101',
MASTER_USER='repl',MASTER_PASSWORD='Root123!', MASTER_LOG_FILE='mysqlbin.000004', MASTER_LOG_POS=0;
master 主机意外停止运行,重启master 需要重新指向master 的二进制文件和pos
change master to master_host='192.168.237.101',master_user='repl',master_password='Root123!',master_log_file='mysql-bin.000007',master_log_pos=154;