Mysql支持单向的异步复制,即一个服务器做主服务器,其他的一个或多个服务器做从服务器。复制是通过二进制日志实现的,主服务器写入,从服务器读取。复制是主从分离的基础,贴一张图说明。
场景描述:
主数据库服务器:192.168.1.100,MySQL已经安装,并且无应用数据。
从数据库服务器:192.168.1.101,MySQL已经安装,并且无应用数据。
主从服务器的Mysql版本最好一致,以免不同版本之间的差异。
主服务器配置
一、为主服务器创建复制的专用用户:
Mysql> CREATE USER 'replicator'@'192.168.1.101' IDENTIFIED BY 'password';
授权:Mysql> grantreplication slave on *.* to ' replicator '@'192.168.1.101' identified by ' password ';
二、确认主服务器上my.cnf文件的[mysqld]section包含log-bin(开启二进制日志)选项和server-id:
[mysqld]
log-bin =/home/mysql/log/mysql-bin.log
server-id=1
修改后需要重启mysql
三、查询主数据库状态
Mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 | 261 | | |
+------------------+----------+--------------+------------------+
记录下 FILE 及 Position的值,在后面进行从服务器操作的时候需要用到。
配置从服务器
一、修改从服务器的配置文件my.cnf
将server-id = 1修改为 server-id = 10,并确保这个ID没有被别的MySQL服务所使用,这个就是从服务器在mysql集群的ID。
重启从服务器。
二、执行同步SQL语句
mysql> changemaster to
master_host=’192.168.1.100’,
master_user=’ replicator’,
master_password=’password’,
master_log_file=’mysql-bin.000005’,
master_log_pos=261;
三、正确执行后启动Slave同步进程
mysql> start slave;
四、主从同步检查
mysql> show slave status\G
==============================================
**************** 1. row *******************
Slave_IO_State:
Master_Host: 192.168.1.100
Master_User: replicator
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000005
Read_Master_Log_Pos: 415
Relay_Log_File: localhost-relay-bin.000008
Relay_Log_Pos: 561
Relay_Master_Log_File: mysql-bin.000005
Slave_IO_Running: YES
Slave_SQL_Running: YES
Replicate_Do_DB:
……………省略若干……………
Master_Server_Id: 1
1 row in set (0.01 sec)
==============================================
其中Slave_IO_Running与 Slave_SQL_Running的值都必须为YES,才表明状态正常。
验证主从复制效果
一、主服务器上的操作
在主服务器上创建数据库first_db
mysql> create database first_db;
Query Ok, 1 row affected (0.01 sec)
在主服务器上创建表first_tb
mysql> create table first_tb(id int(3),name char(10));
Query Ok, 1 row affected (0.00 sec)
在主服务器上的表first_tb中插入记录
mysql> insert into first_tb values (001,’myself’);
Query Ok, 1 row affected (0.00 sec)
二、在从服务器上查看
mysql> show databases;
=============================
+--------------------+
| Database |
+--------------------+
| information_schema |
| first_db |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.01 sec)
=============================
数据库first_db已经自动生成
mysql> use first_db
Database chaged
mysql> show tables;
=============================
+--------------------+
| Tables_in_first_db |
+--------------------+
| first_tb |
+--------------------+
1 row in set (0.02 sec)
=============================
数据库表first_tb也已经自动创建
mysql> select * from first_tb;
=============================
+------+------+
| id | name |
+------+------+
| 1 | myself |
+------+------+
1 rows in set (0.00 sec)
=============================
记录也已经存在
由此,整个MySQL主从复制的过程就完成了