线上不停机部署mysql主从
不影响主库业务情况下构建主从复制步骤
非gtid模式下
更改主库my.cnf
server-id=1 binlog-format = mixed log-bin=mysql-bin datadir=/var/lib/mysql innodb_flush_log_at_trx_commit=1 sync_binlog=1
主库授权账号复制权限
GRANT REPLICATION SLAVE ON *.* TO replicant@% IDENTIFIED BY '<<choose-a-good-password>>'
使用binlog位置创建备份文件。它会影响数据库服务器的性能,但不会锁定表:
mysqldump --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data=2 -A > ~/dump.sql
检查文件的头部并记下MASTER_LOG_FILE和MASTER_LOG_POS的值
head dump.sql -n80 | grep "MASTER_LOG_POS"
修改从库my.cnf
server-id = 101 binlog-format = mixed log_bin = mysql-bin relay-log = mysql-relay-bin log-slave-updates = 1 read-only = 1
重启mysql
导入sql文件
mysql -u root -p < ~/dump.sql
从库设置主库信息:
CHANGE MASTER TO MASTER_HOST='192.168.0.20',MASTER_PORT=5306,MASTER_USER='slave',MASTER_PASSWORD='VsaN4Z8mtE', MASTER_LOG_FILE='slave-bin.000034',MASTER_LOG_POS=271;
start slave;
show slave status;
如果一切正常,则Last_Error将为空,Slave_IO_State将报告“等待主发送事件”。寻找Seconds_Behind_Master,它表明它背后有多远。
## gtid模式下
### 修改my.cnf
server-id = 123456789 //服务 ID,主从实例 server-id 需不同。 log_bin = /var/log/mysql/mysql-bin.log expire_logs_days = 10 max_binlog_size = 100M replicate-do-db = exampledb //需要同步的数据库 replicate-ignore-db = mysql //不需要同步的数据库 replicate-ignore-db = information_schema //不需要同步的数据库 replicate-ignore-db = performance_schema //不需要同步的数据库 #GTID gtid_mode=on enforce_gtid_consistency=on binlog_format=row //设置 binlog 为 row log-slave-updates=1
重启mysql
从库授权:
change master to master_host = 'masterhost.mysql.rds.aliyuncs.com', master_port = 3306, master_user = 'catest', master_password='masterpassword', master_auto_position = 1;
导出主库sql文件
mysqldump -hmasterIP -ucopyuser -p -P3306 --single-transaction --set-gtid-purged=ON testdb > ~/dump.sql
执行sql文件,导入数据
mysql -uroot -p visdb <~/dump.sql
启动slave
start slave;