首页 > 代码库 > MySQL主从复制

MySQL主从复制


 
原理:利用mysql二进制日志文件,实现数据同步
 
步骤:
 
一、配置主库(Master)
 
1. 修改主库my.cnf配置文件,加入如下配置
[root@localhost ~]# nano -w /etc/my.cnf
 
[mysqld] log-bin=mysql-bin server-id=1
 
2. 重启mysql,使配置生效
[root@localhost ~]# service mysqld restart
 
3. 以root登录mysql,创建主从复制用户并授权主从复制
[root@localhost ~]# mysql -uroot -p
 
mysql> CREATE USER ‘repl‘@‘%‘ IDENTIFIED BY ‘repl_password‘;
mysql> GRANT REPLICATION SLAVE ON *.* TO ‘repl‘@‘%‘;
mysql> FLUSH PRIVILEGES;
 
4. 查看主库二进制日志坐标(记住File和Position列对应的值)
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 747      |              |                  |
+------------------+----------+--------------+------------------+

 

 
 
二、配置从库(Slave)
 
1. 修改从库my.cnf配置文件,加入如下配置
[root@localhost ~]# nano -w /etc/my.cnf
 
[mysqld] server-id=2
 
2. 修改MySQL server UUID(可选,如果是直接克隆虚拟机,则这步必须做)
mv /var/lib/mysql/auto.cnf /var/lib/mysql/auto.cnf.bak
 
3. 重启mysql,使配置生效并生成新的MySQL server UUID
[root@localhost ~]# service mysqld restart
 
4. 以root登录mysql,并设置从库访问主库二进制日志文件
[root@localhost ~]# mysql -uroot -p
mysql> CHANGE MASTER TO
    ->    MASTER_HOST=master_host_name,
    ->    MASTER_USER=repl,
    ->    MASTER_PASSWORD=repl_password,
    ->    MASTER_LOG_FILE=mysql-bin.000001,
    ->    MASTER_LOG_POS=747;
 
5. 启动Slave
mysql> start slave;
 
6. 查看Slave连接状态(Slave_IO_Running、Slave_SQL_Running都为Yes则表示连接成功)
mysql> show slave status \G;
 
*************************** 1. row ***************************
  Slave_IO_State: Waiting for master to send event
  Master_Host: 192.168.168.110
  Master_User: repl
  Master_Port: 3306
  Connect_Retry: 60
  Master_Log_File: mysql-bin.000001
  Read_Master_Log_Pos: 747
  Relay_Log_File: localhost-relay-bin.000002
  Relay_Log_Pos: 320
  Relay_Master_Log_File: mysql-bin.000001
  Slave_IO_Running: Yes
  Slave_SQL_Running: Yes
 
 

MySQL主从复制