1. 程式人生 > >MySql5.7.16主從同步

MySql5.7.16主從同步

環境:

1.系統:CentOS7
2.MySql:MySql5.7.16
主(master):192.168.133.161
從(slave):192.168.133.166

步驟

1.兩個伺服器MySql全部關閉
1).my.cnf:
主:
[mysqld]
log-bin=mysql-bin
server-id=1
從:
[mysqld]
server-id=2
註解:server-id必須唯一。如果預設為0,則拒絕連線主伺服器。
2.主:
1).啟動master的Mysql服務
2).建立使用者,讓slave伺服器用來連線用.

CREATE USER 'mysqlUser'@'ip' IDENTIFIED BY 'mysqlPassword';
GRANT REPLICATION SLAVE ON *.* TO 'mysqlUser'@'ip';

例如:
CREATE USER ‘qfmyy’@’192.168.133.%’ IDENTIFIED BY ‘Langman082522’;
GRANT REPLICATION SLAVE ON . TO ‘qfmyy’@’192.168.133.%’;
IP地址可用*表示,用以所有ip都可以連線
註解:簡單建立使用者,授予REPLICATION SLAVE許可權。訪問限制,密碼,使用者名稱等,根據實際情況各自設定
3).獲取日誌座標

設定讀鎖
FLUSH TABLES WITH READ LOCK;
檢視日誌座標
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000006 | 1608 | | | | +------------------+----------+--------------+------------------+-------------------+

記住上面兩個欄位數值

3).匯出master所有資料

mysqldump --all-databases --master-data -uroot -p > /tmp/dbdump.db

然後解鎖:

UNLOCK TABLES;

把dbdump.db複製到slave伺服器的tmp目錄下
3.從:
1).my.cnf檔案下新增
[mysqld]
skip-slave-start=true
read_only=ON
relay-log=relay-bin
relay-log-index=relay-bin.index
2).啟動slave資料庫
3).

CHANGE MASTER TO
MASTER_HOST='IP',
MASTER_USER='mysqlUser',
MASTER_PASSWORD='mysqlPassword',
MASTER_LOG_FILE='日誌File',
MASTER_LOG_POS=日誌Position;

例如:
CHANGE MASTER TO
MASTER_HOST=’192.168.133.161’,
MASTER_USER=’qfmyy’,
MASTER_PASSWORD=’Langman082522’,
MASTER_LOG_FILE=’mysql-bin.000006’,
MASTER_LOG_POS=1608;
4).將/tmp/dbdump.db 匯入資料庫

/bin/mysql -uroot -p < /tmp/dbdump.db

5).檢視slave狀態

show slave status \G

Slave_IO_State:
Master_Host: 192.168.133.161
Master_User: qfmyy
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000006
Read_Master_Log_Pos: 1608
Relay_Log_File: relay-bin.000001
Relay_Log_Pos: 4
Relay_Master_Log_File: mysql-bin.000006
Slave_IO_Running: No
Slave_SQL_Running: No
看到:
Slave_IO_Running: No
Slave_SQL_Running: No
6).啟動slave:

start slave;

Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.133.161
Master_User: qfmyy
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000006
Read_Master_Log_Pos: 1608
Relay_Log_File: relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.000006
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
看到
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
同步成功!

—————————————————————————————

錯誤程式碼:
1130:原因有多種
1).沒有徹底關閉selinux防火牆原因

vim /etc/sysconfig/selinux

SELINUX=enforcing 隱藏
SELINUXTYPE=targeted  隱藏
SELINUX=disabled

這個要重啟伺服器
2).執行訪問ip段
主:

update user set host = '%' where user ='mysqlUser';
flush privileges;

例如:update user set host = ‘%’ where user =’qfmyy’;
1593:由於克隆虛擬機器原因,導致
這裡寫圖片描述
相同:
vim 資料存放地址/auto.cnf
隨便修改service-uuid的值
如:
這裡寫圖片描述
重啟mysql