1.理解MySQL主从复制原理
1、master(binlog dump thread)主要负责Master库中有数据更新的时候,会按照binlog格式,将更新的事件类型写入到主库的binlog文件中。
2、I/O thread线程在Slave中创建,该线程用于请求Master,Master会返回binlog的名称以及当前数据更新的位置、binlog文件位置的副本。将binlog保存在 「relay log(中继日志)」 中
3、SQL线程也是在Slave中创建的,当Slave检测到中继日志有更新,就会将更新的内容同步到Slave数据库中,这样就保证了主从的数据的同步
2.完成MySQL主从复制
环境准备
两台机器一主一从
由于服务器是克隆复制的,要更改从库的uuid
[root@localhost ~]# vim /var/lib/mysql/auto.cnf[auto]
server-uuid=892dc96a-1b13-11ee-b662-000c29aba114
1、设置主从库的server-id值并开启binlog参数(从可以不用开启binlog)
[root@localhost ~]# vim /etc/my.cnflog_bin=mysql-bin
server-id=140 # 主从的server-id唯一
2、在主库上建立同步账号
mysql> grant replication slave on *.* to 'user'@'192.168.159.%' identified by '12345';
Query OK, 0 rows affected, 1 warning (0.00 sec)
3、 备份主库数据
[root@localhost ~]# mysql -uroot -p12345 -e 'show databases'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| db |
| mysql |
| performance_schema |
| school |
| sys |
+--------------------+[root@localhost ~]# mysqldump -uroot -p -A -B |gzip > db.sql.gz
Enter password:
4、主库备份数据上传到从库
[root@localhost ~]# scp db.sql.gz 192.168.159.141:/root/
root@192.168.159.141's password:
db.sql.gz 100% 205KB 68.4MB/s 00:00
5、还原从主库备份数据
[root@localhost ~]# zcat db.sql.gz | mysql -uroot -p12345
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# mysql -uroot -p12345 -e 'show databases'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| db |
| mysql |
| performance_schema |
| school |
| sys |
+--------------------+
6、查看主库状态
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000007 | 742 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
7、设定从主库同步
mysql> change master to-> MASTER_HOST='192.168.159.140',-> MASTER_PORT=3306,-> MASTER_USER='user',-> MASTER_PASSWORD='12345',-> MASTER_LOG_FILE='mysql-bin.000007',-> MASTER_LOG_POS=742;
Query OK, 0 rows affected, 2 warnings (0.00 sec)
8、重启数据库
[root@localhost ~]# systemctl restart mysqld
9、启动从库同步开关并检查状态
mysql> start slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show slave status\G
当都为yes是即成功
测试
问题:
当IO为connecting时,是由于没有关闭防火墙。关闭防火墙即可。