項目環境:
系統:CentOS7.6
數據庫版本: MySQL 5.7
關閉:firewalld
關閉:selinuxmysql
MySQL主從複製流程簡介
一、主:記錄全部改變了的數據的語句,放進masert上的binlog中;
二、從:io線程——在使用start slave以後,負責從masert上拉取binlog內容,返回io線程,最後放進本身的relay log中;
三、從:sql執行線程會讀取中繼日誌——執行relay log中的語句。
注意:是從服務器去主服務器抓取二進制日誌再放到本身的中繼日誌裏,sql線程會一直讀取本身的中繼日誌。linux
主庫:192.168.1.31sql
準備一個庫(素材)
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.cnfvim
[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=mysqlsocket
[mysqld_safe]
log-error=/usr/local/mysql/logs/error.log
pid-file=/usr/local/mysql/mysql.pidide
[client]
socket=/usr/local/mysql/mysql.sock測試
重啓數據庫
[root@MySQLDB1 ~]# /etc/init.d/mysqld restart線程
登陸數據庫內建立用戶(slave從庫)受權訪問
mysql> grant replication slave on *.* to slave@192.168.1.32 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