mysql主从复制实战
主机规划
主:172.16.1.51 db01
从:172.16.1.52 db02
需求:mysql主库用户写入数据实时同步到从库、这里演示1主1从。
1、主机开启bin-log功能
[[email protected] ~]# egrep log_bin /etc/my.cnf
log_bin
2、主从server-id不同、主从/etc/my.cnf必须有server-id
[[email protected] ~]# egrep server-id /etc/my.cnf
server-id = 6
[[email protected] ~]# egrep server-id /etc/my.cnf
server-id = 7
3、主库创建授权用户
[[email protected] ~]# mysql -uroot -poldboy123
mysql> grant replication slave on *.* to ‘rep‘@‘172.16.1.%‘ identified by ‘oldboy123‘;
mysql> flush privileges;
4、使用mysqldump备份截止当前日期的数据
1.锁表停止用户继续写入
mysql> flush table with read lock; # 备份时锁表、不能退出mysql。
mysql> show master status; # 查看主状态
+-------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| db01-bin.000001 | 120 | | | |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.08 sec)
2.单开xshell/CRT窗口开始备份
[[email protected] ~]# mysqldump -uroot -poldboy123 -A -B --master-data=2|gzip >/opt/db01.sql.gz
[[email protected] ~]# gzip -d /opt/db01.sql.gz
[[email protected] ~]# scp /opt/db01.sql 172.16.1.52:/opt/ #<==发送备份到从库
3.原窗口取消锁表
mysql> unlock table;
5、从库开始恢复主库
[[email protected] ~]# mysql -uroot -poldboy123 </opt/db01.sql
6、从库指定主机、用户、位置点同步数据库操作
mysql> CHANGE MASTER TO
MASTER_HOST=‘172.16.1.51‘, #<==主机IP
MASTER_PORT=3306, #<==端口
MASTER_USER=‘rep‘, #<==主机管理用户
MASTER_PASSWORD=‘oldboy123‘, #<==密码
MASTER_LOG_FILE=‘db01-bin.000001‘, #<==binlog文件
MASTER_LOG_POS=120; #<==binlog pos值
7、从库开启同步开关,检查是否同步
mysql> start slave;
mysql> show slave status\G
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
提示:show slave status\G出来的结果包含以上三条内容为成功!
8、验证主从复制是否成功
**主:db01
mysql> create database lmin;
Query OK, 1 row affected (0.00 sec)
**从:db02
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| lmin |
| mysql |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)
主从复制配置完毕!
说明:mysql主从复制不难,一主多从,多主多从、配置方法差不太多!