项目环境:
系统:CentOS7.6
数据库版本: MySQL 5.7
关闭:firewalld
关闭:selinux
MySQL主从复制流程简介
1、主:记录所有改变了的数据的语句,放进masert上的binlog中;
2、从:io线程——在使用start slave之后,负责从masert上拉取binlog内容,返回io线程,最后放进自己的relay log中;
3、从:sql执行线程会读取中继日志——执行relay log中的语句。
注意:是从服务器去主服务器抓取二进制日志再放到自己的中继日志里,sql线程会一直读取自己的中继日志。
主库:192.168.1.31
准备一个库(素材)
mysql> create database test; #创建一个库用作测试
mysql> use test; #选择test库
mysql> create table emp (empno numeric(4) not null,ename varchar(10),job varchar(9),mgr numeric(4),hiredate datetime,sal numeric(7,2),comm numeric(7,2),deptno numeric(2)); #在test库里创建一张表
mysql> insert into emp values(7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, null, 20); #插入一条语句
写配置文件
[root@MySQLDB1 ~]# vim /etc/my.cnf
[mysqld]
datadir=/usr/local/mysql/data
socket=/usr/local/mysql/mysql.sock
#symbolic-links=0
#master and slave
log-bin=mysql-bin-master
server-id=1
binlog-do-db=test
binlog-ignore-db=mysql
[mysqld_safe]
log-error=/usr/local/mysql/logs/error.log
pid-file=/usr/local/mysql/mysql.pid
[client]
socket=/usr/local/mysql/mysql.sock
重启数据库
[root@MySQLDB1 ~]# /etc/init.d/mysqld restart
登录数据库内创建用户(slave从库)授权访问
mysql> grant replication slave on *.* to [email protected] identified by "123456";
mysql> flush privileges; #刷新权限
mysql> select * from mysql.user where user='slave'\G; #查看一下权限
Repl_slave_priv: Y #复制的权限
mysql> show master status; #查看一下状态信息
+-------------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------------+----------+--------------+------------------+-------------------+
| mysql-bin-master.000004 | 601 | test | mysql | |
+-------------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
从库:192.168.1.32
写从库的配置文件
[root@MySQLDB2 ~]# vim /etc/my.cnf
[mysqld]
datadir=/usr/local/mysql/data
socket=/usr/local/mysql/mysql.sock
symbolic-links=0
server-id=2
[mysqld_safe]
log-error=/usr/local/mysql/logs/error.log
pid-file=/usr/local/mysql/mysql.pid
[client]
socket=/usr/local/mysql/mysql.sock
重启数据库
[root@MySQLDB2 ~]# /etc/init.d/mysqld restart
测试登录主库的slave账号成功!
[root@MySQLDB2 ~]# mysql -uslave -p123456 -h192.168.1.31
mysql> exit;
登录身的root账号做同步
[root@MySQLDB2 ~]# mysql -uroot -p123456
mysql> stop slave; #先停止从库账号
授权master可以访问从
mysql> change master to master_host='192.168.1.31',master_port=3306,master_user='slave',master_password='123456',master_log_file='mysql-bin-master.000004',master_log_pos=601;
开启slave用户
mysql> start slave;
mysql> show slave status \G #查看同步成功了吗?
Slave_IO_Running: Yes #出现这两个说明主从同步成功了
Slave_SQL_Running: Yes