数据库主从复制简单配置

1、主从原理

从《高性能mysql》书中讲解主从原理大致有三个步骤:

在主库上把数据更改记录到二进制日志中(Binary Log)中,这些记录称为二进制日志事件。
从库通过IO线程将主库上的日志复制到自己的中继日志(Relay Log)中。
从库通过SQL线程读取中继日志中的事件,将其重放到自己数据上。
原理图为:


2、主从配置

演示的环境如下:

名称 IP
msyql-master(主库) 192.168.82.112
mysql-slave(从库) 192.168.194.12

(1)、配置主库

  • 修改my.cnf文件,在[mysqld]加入下面的内容:

    # 服务的唯一编号
    server-id = 1
    
    # 开启mysql binlog功能
    log-bin = mysql-bin
    
    # binlog记录内容的方式,记录被操作的每一行
    binlog_format = ROW
    
    # 减少记录日志的内容,只记录受影响的列
    binlog_row_image = minimal
    
    # 指定需要复制的数据库名为mytest
    binlog-do-db = mytest
    
    
  • 修改好配置文件,重启mysql服务

    service mysqld restart
    
    
  • 创建从库同步数据的账号

    grant replication slave on *.* to 'test123'@'192.168.197.136' identified by 'test@123';
    flush privileges;
    
    

    注意:上面这两个命令是在mysql的终端执行的。

  • 查看主库的状态:

    mysql的终端执行:

    show master status\G;
    
    

    返回的信息为:

    *************************** 1\. row ***************************
                 File: mysql-bin.000071
             Position: 623
         Binlog_Do_DB: mytest
     Binlog_Ignore_DB: 
    Executed_Gtid_Set: 
    1 row in set (0.00 sec)
    
    

注意:这个623和mysql-bin.000071配置从库需要用到

(2)、配置从库

  • 修改my.cnf文件,在[mysqld]加入下面的内容:

    # 服务的唯一编号
    server-id = 2
    
    # 开启mysql binlog功能
    log-bin = mysql-bin
    
    # binlog记录内容的方式,记录被操作的每一行
    binlog_format = ROW
    
    # 减少记录日志的内容,只记录受影响的列
    binlog_row_image = minimal
    
    # 指定需要复制的数据库名为mytest
    replicate-do-db = mytest
    
    
  • 修改好配置文件,重启mysql服务

    service mysqld restart
    
    
  • 执行同步命令

    mysql的终端执行:

    # 设置主服务器ip,同步账号密码,同步位置
    change master to master_host='192.168.82.112',master_user='test123',master_password='test@123',master_log_file='mysql-bin.000071',master_log_pos=623;
    
    # 开启同步功能
    start slave;
    
    
  • 查看从库的状态

    mysql的终端执行:

    show slave status\G;
    
    

    返回信息为:

image

注意:Slave_IO_Running和Slave_SQL_Running的状态都为Yes时,说明从库配置成功。

3、测试

(1)进入主库的mytest数据库,

use mytest;

(2)、在主库上的mytest数据库创建comm_config表,即:

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('name', '主从复制', '测试一下');

(4)、在从库上进入mytest数据库,并查看数据表

use mytest;
show tables;

(5)、在从库上查看jgyw模式下的表及数据,即:

use jgyw;
show tables;

结果为:


image.png

说明表同步好了,再查看数据,即:

select * from comm_config;

结果为:

+----------+--------------+--------------+
| configId | configValue  | description  |
+----------+--------------+--------------+
| name     | 主从复制     | 测试一下     |
+----------+--------------+--------------+
1 row in set (0.00 sec)

说明数据也同步过来了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容