MySQL 5.7.18 主从配置

June 26, 2017 9:14 AM

主库

在 my.cnf 中添加配置项

[mysqld]
server_id = 1
binlog-do-db = test #需要同的数据库
log_bin = mysql-bin # 开启log_bin

创建同步用户

mysql> grant replication slave on *.* to 'repl'@'192.168.1.%' identified by 'repl..2017';

查看 master 状态

mysql> show master status \G;
*************************** 1. row ***************************
             File: mysql-bin.000002
         Position: 4707
     Binlog_Do_DB: test
 Binlog_Ignore_DB: 
Executed_Gtid_Set: 
1 row in set (0.00 sec)

重启

service mysqld restart

从库

在 my.cnf 中添加配置项

[mysqld]
server_id = 2   #服务器id,必须唯一
replicate-do-db = test  # 需要同步的数据库

重启

service mysqld restart

连接主库

mysql > change master to master_host='192.168.1.151',master_port=3306,master_user='repl',master_password='repl',master_log_file='mysql-bin.000002',master_log_pos=3703;
  • master_host 主库地址
  • master_port 主库端口
  • master_user 主库提供的同步用户
  • master_password 主库提供的同步用户密码
  • master_log_file 在主库中查看 master 状态中的 file
  • master_log_pos 在主库中查看 master 状态中的 position

启动主从同步

mysql > start slave;

** 查看同步状态**

mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.151
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 4707
               Relay_Log_File: localhost-relay-bin.000004
                Relay_Log_Pos: 1503
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: test
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 

1 row in set (0.00 sec)

# 状态中,`Slave_IO_Running: Yes` 和 `Slave_SQL_Running: Yes` 同时保证为 yes 即可判断成功。

多进程主从复制

stop slave;
set global slave_parallel_type='logical_clock';
set global slave_parallel_workers=8;
start slave;
show processlist;