mysql主从复制原理:
1.两个文件:master.info 上次从master上取到bin-log记录
relay-log.info 存放取来的log
2.三个线程:
2个I/O线程1个SQL线程
3.配置过程
主库操作:
1>开启binlog 设置server-id
[root@localhost mysql]# vi /etc/my.cnf
# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin //开启binlog
# binary logging format - mixed recommended
binlog_format=mixed
# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id = 1 //设置 id
2>授权访问
mysql> grant replication slave on *.* to wyg@'%' identified by '123456';
mysql> flush privileges;
3>主库锁表备份
mysql> flush tables with read lock;
测试锁表成功
mysql> create database qq;
ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock
备份数据
[root@localhost mysql]# mysqldump -uroot -p123456 -A -B >/tmp/all.sql
查看主库记住log点及解锁
mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 | 459 | | |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
mysql> unlock table;
Query OK, 0 rows affected (0.00 sec)
4.从库操作
1>设置server-id = 3 与主库不同
2>恢复主库数据
[root@localhost data]# mysql -uroot -p123456 </tmp/all.sql
mysql> CHANGE MASTER TO MASTER_HOST='172.31.82.83',MASTER_PORT=3306,MASTER_USER='wyg',MASTER_PASSWORD='123456',MASTER_LOG_FILE='mysql-bin.000005',MASTER_LOG_POS=459;
3>开启slave
mysql> start slave;
Query OK, 0 rows affected (0.01 sec)
4>查看slave
mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 172.31.82.83
Master_User: wyg
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000005
Read_Master_Log_Pos: 459
Relay_Log_File: localhost-relay-bin.000002
Relay_Log_Pos: 251
Relay_Master_Log_File: mysql-bin.000005
Slave_IO_Running: Yes //一定是yes
Slave_SQL_Running: Yes //一定是yes
Replicate_Do_DB:
如有不是yes检查两台主机是否通讯,查看iptables 和selinux
5.主库创建数据库,从库查看
主库创建
mysql> create database nihao;
Query OK, 1 row affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
从库查看
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| funtalk |
| mysql |
| nihao |
| test |
| tt |
+--------------------+
6 rows in set (0.00 sec)
到次 mysql主从复制完成。