MySQL 8.0 主從同步

一.簡介

    一台伺服器充當主資料庫伺服器,另一台或多台伺服器充當從資料庫伺服器,主伺服器中的數據自動複製到從伺服器之中。MySQL主從複製的基礎是主伺服器對資料庫修改記錄二進位日誌,從伺服器通過主伺服器的二進位日誌自動執行更新。

環境:

  主庫主機(master): 172.17.7.21
  從庫主機(slave): 172.17.7.20

二.步驟

  1.mysql 配置文件

 

        (1)、打開master的配置文件my.cnf    

 1 [mysqld]
 2 server-id = 1        # 節點ID,確保唯一
 3 
 4 # log config
 5 log-bin = mysql-bin     #開啟mysql的binlog日誌功能
 6 sync_binlog = 1         #控制資料庫的binlog刷到磁碟上去 , 0 不控制,性能最好,1每次事物提交都會刷到日誌文件中,性能最差,最安全
 7 binlog_format = mixed   #binlog日誌格式,mysql默認採用statement,建議使用mixed
 8 expire_logs_days = 7                           #binlog過期清理時間
 9 max_binlog_size = 100m                    #binlog每個日誌文件大小
10 binlog_cache_size = 4m                        #binlog快取大小
11 max_binlog_cache_size= 512m              #最大binlog快取大
12 binlog-ignore-db=mysql #不生成日誌文件的資料庫,多個忽略資料庫可以用逗號拼接,或者 複製這句話,寫多行
13 auto-increment-offset = 1     # 自增值的偏移量
14 auto-increment-increment = 1  # 自增值的自增量
15 slave-skip-errors = all #跳過從庫錯誤

View Code

   (2)、打開slave的配置文件my.cnf    

1 [mysqld]
2 server-id = 2
3 log-bin=mysql-bin
4 relay-log = mysql-relay-bin
5 replicate-wild-ignore-table=mysql.%
6 replicate-wild-ignore-table=test.%
7 replicate-wild-ignore-table=information_schema.%

View Code

   (3)、重啟mysql (net stop mysql、net start MySQL)

 

  2.master資料庫,創建複製用戶並授權

 

   (1)、進入master的資料庫,為master創建複製用戶

create user 'slaveuser'@'172.17.7.20' identified by 'ysp_password';

   

grant replication slave on *.* to 'slaveuser'@'172.17.7.20' 
FLUSH PRIVILEGES;

     (2)、查看master的狀態

 

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001      782|              | mysql            |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

  

  3.slave資料庫

   

mysql> CHANGE MASTER TO 
MASTER_HOST = '172.17.7.21',  
MASTER_USER = 'slaveuser', 
MASTER_PASSWORD = 'ysp_password',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=782;

# MASTER_LOG_FILE='mysql-bin.000001',#與主庫File 保持一致
# MASTER_LOG_POS=782 , #與主庫Position 保持一致

   (1)、啟動從庫slave進程

mysql> start slave;
Query OK, 0 rows affected (0.04 sec)

   (2)、查看主從同步狀態

mysql> show slave status\G

   開啟主從之後,如果狀態如上圖所示,那麼說明主從資訊就已經配置好了

 

Tags: