1、主从原理
主从原理大致有三个步骤:
- 在主库上把数据更改记录到二进制日志中(Binary Log)中,这些记录称为二进制日志事件。
- 从库通过IO线程将主库上的日志复制到自己的中继日志(Relay Log)中。
- 从库通过SQL线程读取中继日志中的事件,将其重放到自己数据上。
原理图为:
2、主从配置
演示的环境如下:
名称 | IP |
---|---|
msyql-master(主库) | 192.168.197.135 |
mysql-slave(从库) | 192.168.197.136 |
之后在这两台服务器安装mysql数据库。
(1)、配置主库
-
修改my.cnf文件,在[mysqld]加入下面的内容:
# 服务的唯一编号 server-id = 1 # 开启mysql binlog功能 log-bin = mysql-bin # binlog记录内容的方式,记录被操作的每一行 binlog_format = ROW # 减少记录日志的内容,只记录受影响的列 binlog_row_image = minimal # 指定需要复制的数据库名为jgyw binlog-do-db = jgyw
修改好配置文件,重启mysql服务
service mysqld restart
创建从库同步数据的账号
grant replication slave on *.* to 'jgyw'@'192.168.197.136' identified by 'jgyw@123'; flush privileges;
-
注意:上面这两个命令是在mysql的终端执行的。
-
查看主库的状态:
mysql的终端执行:
show master statusG;
返回的信息:
*************************** 1. row *************************** File: mysql-bin.000002 Position: 2380 Binlog_Do_DB: jgyw Binlog_Ignore_DB: Executed_Gtid_Set: 1 row in set (0.00 sec)
(2)、配置从库
-
修改my.cnf文件,在[mysqld]加入下面的内容:
# 服务的唯一编号 server-id = 2 # 开启mysql binlog功能 log-bin = mysql-bin # binlog记录内容的方式,记录被操作的每一行 binlog_format = ROW # 减少记录日志的内容,只记录受影响的列 binlog_row_image = minimal # 指定需要复制的数据库名为jgyw replicate-do-db = jgyw
修改好配置文件,重启mysql服务
service mysqld restart
执行同步命令
mysql的终端执行:
# 设置主服务器ip,同步账号密码,同步位置 change master to master_host='192.168.197.135',master_user='jgyw',master_password='jgyw@123',master_log_file='mysql-bin.000002',master_log_pos=2380; # 开启同步功能 start slave;
注意:这里配置的各种信息与master数据库对应,如master_host(主服务器host)、master_user(主服务器账户)、master_password(主服务器密码)、master_log_file(主服务器的二进制文件)、master_log_pos(主服务器log的位置)等值。与上述的主库对应。
查看从库的状态
mysql的终端执行:
show slave statusG;
-
返回信息为:
注意:Slave_IO_Running和Slave_SQL_Running的状态都为Yes时,说明从库配置成功。
3、测试
(1)、在主库上创建jgyw模式,即:
create schema jgyw;
(2)、在主库上的jgyw模式里面创建comm_config表,即:
use jgyw; CREATE TABLE comm_config (configId varchar(200) NOT NULL ,configValue varchar(1024) DEFAULT NULL ,description varchar(2000) DEFAULT NULL ,PRIMARY KEY (configId)) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
(3)、在主库上往comm_config表中插入一条记录,即:
insert into comm_config(configId, configValue, description) values('user', '架构设计', '测试');
(4)、在从库上查看模式,即:
show schemas;
结果为:
+--------------------+ | Database | +--------------------+ | information_schema | | jgyw | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.00 sec)
说明jgyw模式同步到从库了
(5)、在从库上查看jgyw模式下的表及数据,即:
use jgyw;
show tables;
结果为:
+----------------+ | Tables_in_jgyw | +----------------+ | comm_config | +----------------+ 1 row in set (0.00 sec)
说明表也同步好了,再查看数据,即:
select * from comm_config;
结果为:
+----------+--------------+--------------+ | configId | configValue | description | +----------+--------------+--------------+ | user | 架构设计 | 测试 | +----------+--------------+--------------+ 1 row in set (0.00 sec)
说明数据也同步过来了。