mysql主從同步

MySQL主從介紹

MySQL主從叫做Replication、AB複製,A和B做主從後,在A上寫數據。B上也會同步A的數據,兩者實現實時同步
MySQL是基於binlog日誌來同步的,主上必須開啓binlog才能進行主從同步,同步過程大概有三個步驟
(1)主將數據操作更改的記錄到binlog中
(2)主從之間同步比較binlog的事件記錄,A將事件記錄到binlog裏,從同步到本地後也會在本機上記錄一個relaylog的文件
(3)從根據relaylog裏面的事件記錄來執行同步
主上有一個log dump的線程,用來和從的I/O線程傳遞binlog
從上會有兩個線程,其中I/O線程用於同步binlog的記錄併產生relaylog記錄,另一個SQL線程用來執行relaylog中的事務,把SQL數據在主上按大小、改變、來一一同步
主從同步有兩種場景模式
主-從:主負責所有的數據查詢和更改,從只負責數據的備份,只起到備份的作用
主寫-從讀:主負責數據來源的存儲和修改,不用於數據查詢。從不僅起到實時備份的作用,還對外部提供查詢數據的訪問,這樣可以減小主數據庫的訪問壓力

主從數據庫準備
安裝mysql數據庫可以參考另一篇文章
對mysql的編譯安裝參數參考:

[root@localhost mysql-5.7.22]# cmake . -DCMALE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/var/mysql/data -DSYSCONFDIR=/etc -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_ARCHIVE_STORAGE_ENGINE=1 -DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH-SYSTEMD=1 -DWITH_BOOST=/usr/local/boost
-----------------------省略過程----------------------
-- CMAKE_C_LINK_FLAGS: 
-- CMAKE_CXX_LINK_FLAGS: 
-- CMAKE_C_FLAGS_RELWITHDEBINFO: -O3 -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing -DDBUG_OFF
-- CMAKE_CXX_FLAGS_RELWITHDEBINFO: -O3 -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing -DDBUG_OFF
-- Configuring done
-- Generating done
-- Build files have been written to: /usr/local/src/mysql-5.7.22
[root@localhost mysql-5.7.22]# echo $?
0

結果無報錯,繼續make編譯

[root@localhost mysql-5.7.22]# make
Scanning dependencies of target abi_check
[ 0%] Built target abi_check
Scanning dependencies of target INFO_SRC
[ 0%] Built target INFO_SRC
Scanning dependencies of target INFO_BIN
[ 0%] Built target INFO_BIN
Scanning dependencies of target zlib
----------------省略過程------------------------
[ 99%] Building C object libmysqld/examples/CMakeFiles/mysql_client_test_embedded.dir/__/__/testclients/mysql_client_test.c.o
[ 99%] Linking CXX executable mysql_client_test_embedded
[ 99%] Built target mysql_client_test_embedded
Scanning dependencies of target my_safe_process
[100%] Building CXX object mysql-test/lib/My/SafeProcess/CMakeFiles/my_safe_process.dir/safe_process.cc.o
[100%] Linking CXX executable my_safe_process
[100%] Built target my_safe_process
[root@localhost mysql-5.7.22]# aecho $?
0

安裝無報錯,完成最後安裝make install

-----------------------過程省略---------------------
-- Installing: /usr/local/mysql/support-files/mysqld_multi.server
-- Installing: /usr/local/mysql/support-files/mysql-log-rotate
-- Installing: /usr/local/mysql/support-files/magic
-- Installing: /usr/local/mysql/share/aclocal/mysql.m4
-- Installing: /usr/local/mysql/support-files/mysql.server
[root@localhost mysql-5.7.22]# echo $?
0

基本的安裝完成,接下來就是配置mysql的啓動和配置項
遞歸指定mysql所屬用戶和所屬組的權限

[root@localhost ]# chown -R mysql:mysql /usr/local/mysql/

數據庫的初始化
編譯好的數據庫進行初始化,其中mysql初始化信息中包含一個隨機生成的密碼

[root@localhost mysql-5.7.22]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data
2018-07-28T09:08:42.088874Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2018-07-28T09:08:42.590615Z 0 [Warning] InnoDB: New log files created, LSN=45790
2018-07-28T09:08:42.861362Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2018-07-28T09:08:42.955937Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: d342a57c-9245-11e8-bf5e-080027a7f9c2.
2018-07-28T09:08:42.965634Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2018-07-28T09:08:42.966858Z 1 [Note] A temporary password is generated for root@localhost: tHuQg=%M!12j

my.cnf和/etc/init.d/mysqld文件
拷貝服務啓動文件,並修改my.cnf配置文件。指定mysql安裝路徑和存儲數據的路徑及添加系統服務

[root@localhost ]# cp /usr/local/src/mysql-5.7.22/support-files/mysql.server /etc/init.d/mysqld
[root@localhost ]# vim /etc/init.d/mysqld 
~
basedir=/usr/local/mysql/
datadir=/usr/local/mysql/data/
~
[root@localhost ]# chmod +x /etc/init.d/mysqld 
[root@localhost ]# ls -l /etc/init.d/mysqld 
-rwxr-xr-x 1 root root 10609 7月 28 17:21 /etc/init.d/mysqld
[root@localhost ]# chkconfig --add mysqld
[root@localhost ]# chkconfig --list 

注意:該輸出結果只顯示 SysV 服務,並不包含原生 systemd 服務。SysV 配置數據可能被原生 systemd 配置覆蓋。 
      如果您想列出 systemd 服務,請執行 'systemctl list-unit-files'。
      欲查看對特定 target 啓用的服務請執行
      'systemctl list-dependencies [target]'。
mysqld 0:關  1:關 2:開 3:開 4:開 5:開 6:關
netconsole 0:關  1:關 2:關 3:關 4:關 5:關 6:關
network 0:關 1:關 2:開 3:開 4:開 5:開 6:關

編輯my.cnf的mysql配置文件,log-error是記錄啓動時報錯的錯誤信息。在報錯pid的錯誤中,有嘗試把basedir = 的配置給註釋掉,然後mysql能正常啓動了,查看錯誤日誌記錄,日誌記錄報錯unknown variable /usr/local/mysql/ 未知的變量路徑,說明my.cnf指定的路徑有問題,這裏我直接註釋掉basedir這個路徑,然後啓動成功

[root@localhost ]# less /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql/  
datadir = /usr/local/mysql/data  
port = 3306  
character-set-server = utf8  
explicit_defaults_for_timestamp = true  
# socket = /var/run/mysqld/mysqld.sock 
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
log-error = /data/mysql/logs/error.log
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

mysql的啓動過程
添加完成跟隨系統啓動後,啓動mysql服務:

[root@localhost ]# /etc/init.d/mysqld start
Starting MySQL.2018-07-28T09:23:23.822700Z mysqld_safe error: log-error set to '/var/log/mariadb/mariadb.log', however file don't exists. Create writable for user 'mysql'.
 ERROR! The server quit without updating PID file (/usr/local/mysql/data/localhost.pid).

根據報錯提示創建了mysql的日誌文件,然後再嘗試啓動

[root@localhost ]# mkdir -p /var/log/mariadb/mariadb
[root@localhost ]# touch /var/log/mariadb/mariadb.log
[root@localhost ]# chown -R mysql:mysql /var/log/mariadb/mariadb

再次嘗試啓動mysql服務,並啓動成功

[root@localhost support-files]# /etc/init.d/mysqld start
Starting MySQL. SUCCESS! 
[root@localhost support-files]# ps -aux |grep mysql
root 21812 0.0 0.1 113312 1636 pts/0 S 17:28 0:00 /bin/sh /usr/local/mysql//bin/mysqld_safe --datadir=/usr/local/mysq/data --pid-file=/usr/local/mysql/data/localhost.pid
mysql 22000 1.7 16.3 1112372 166604 pts/0 Sl 17:28 0:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql//lib/plugin --user=mysql --log-error=/var/log/mariadb/mariadb.log --pid-file=/usr/local/mysql/data/localhost.pid --port=3306
root 22030 0.0 0.0 112724 976 pts/0 R+ 17:28 0:00 grep --color=auto mysql

將mysql命令寫入系統文件中,這樣就能在命令行中直接使用mysql這個命令了

[root@localhost mysql]# echo "export PATH=$PATH:/usr/local/mysql/bin/" >>/etc/profile
[root@localhost mysql]# source /etc/profile
[root@localhost mysql]# echo "/usr/local/mysql/lib/" >>/etc/ld.so.conf
[root@localhost mysql]# ldconfig

建立master和slave的主從通信

步驟一

master主配置

清除iptables防火牆規則,由於沒有清除iptables。導致進來的數據被轉發重定向到其他IP地址上了

[root@aaa ~]# iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target prot opt in out source destination         
 4811 348K ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
    1 84 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0           
    4 324 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0           
    2 104 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
13467 1028K REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target prot opt in out source destination         
    0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT 3311 packets, 1476K bytes)
 pkts bytes target prot opt in out source destination         
[root@aaa ~]# iptables -F

安裝完mysql後,對my.cnf配置文件進行修改,添加binlog日誌的記錄,指定主從運行時的serverID。
修改my.cnf,添加binlog日誌的產生配置並指定mysql的運行server級別ID
如果只同步或不同步的庫,就需要在my.cnf中指定不同步或同步的庫
#binlog-do-db=db1        #只針對指定庫同步
#binlog-ignore-db=mysql    針對某些庫不同步

[root@aaa /]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql/
datadir = /usr/local/mysql/data
port = 3306
character-set-server = utf8
explicit_defaults_for_timestamp = true
server-id = 10
log-bin = zidingyi

在數據庫中創建一個從數據庫使用訪問的授權用戶,用於從在master中讀取數據並進行同步的作用

mysql> grant replication slave on *.* to 'repl'@192.168.1.220 identified by 'xiangchen' ;
Query OK, 0 rows affected, 1 warning (0.00 sec)

查看主數據庫中的binlog存儲的值,這個是用於記錄數據存儲大小的記錄的,如果數據表發生讀寫變化,這裏也會發生改變。在主從同步前需要在主庫鎖錶停止數據庫讀寫。file是指定生成binlog文件的名稱,Position是數據存儲的變化值,通過這個值來進行同步,這個值也表達了binlog文件的改變大小

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

將主庫鎖表暫時禁止讀取寫入

mysql> flush tables with read lock;
Query OK, 0 rows affected (0.01 sec)

步驟二

slave從配置

slave角色上同樣需要清除iptables規則,以免主從之間無法通信
slave從上配置my.cnf,修改server-id,這個id不能小於主上的配置,數值越小優先級越高。從服務器的my.cnf不需要配置log-bin,因爲是slave的角色,所以只需要從master那裏同步數據即可

[root@Huaching-2 ~]# vim /etc/my.cnf
[mysqld]
#bashdir = /usr/local/mysql/
datadir = /data/mysql
port = 3306
character-set-server = utf8
explicit_defaults_for_timestamp = true
server-id = 20

重啓後登入從數據庫中,先暫停slave的角色,並在數據庫中寫入與master通信的一些信息(binlog記錄的數值)。
master_log_file是指定主上生成binlog文件的名稱,slave會通過這個名稱去找對應的binlog文件。
master_log_pos是指定master數據存儲的變化值,通過這個值來進行同步,這個值也表達了binlog文件的改變大小

[root@Huaching-2 ~]# /etc/init.d/mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL.. SUCCESS! 
mysql> stop slave ;
Query OK, 0 rows affected (0.01 sec)
mysql> change master to master_host='192.168.1.234', master_port=3306, master_user='slave', master_password='xiangchen', master_log_file='zidingyi.000001', master_log_pos=1108;
Query OK, 0 rows affected, 2 warnings (0.02 sec)

步驟三

解除master表鎖和啓動slave角色,進行數據同步

設置好master和slave的授權和訪問賬戶設置後,解除master的表鎖和啓動slave的角色,並把master中的庫拷貝到slave中,這樣才能夠保證啓動同步時兩邊數據的一致性
在解除master的表鎖之前,拷貝master數據到slave中,忽略明文密碼的警告

[root@aaa ~]# mysqldump -uroot -ppwd@123 mysql2 > my2.db
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@aaa ~]# mysqldump -uroot -ppwd@123 zrlog > zrlog.db
mysqldump: [Warning] Using a password on the command line interface can be insecure.

將以db結尾的後綴備份文件通過scp、rzsz或者ftp等方法傳輸到slave上,slave在庫中需要創建需要恢復庫的一個空庫,用於數據導入

mysql> create database mysql2;
Query OK, 0 rows affected (0.02 sec)
mysql> create database zrlog;
Query OK, 0 rows affected (0.02 sec)
mysql> exit
Bye
[root@Huaching-2 ~]#  mysql -uroot -ppwd@123 mysql2 < my2.db
[root@Huaching-2 ~]# mysql -uroot -ppwd@123 zrlog < zrlog.db 

master上可以把數據表鎖解除掉,讓主數據庫可以正常讀寫訪問

mysql> unlock tables;
mysql> flush privileges;

在從數據庫啓用slave的角色,並與master數據庫進行數據同步(數據同步前兩個數據庫數據必須一致,否則同步會造成數據不一樣的情況發生)

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

查看主從同步的信息,這裏主要關注 Slave_IO_Running: Yes和 Slave_SQL_Running: Yes這兩個值,一個表示是否和master正常通信的狀態,Slave_IO是和master的IO進程通信的一個線程,yes表示在正常運行。另一個是表示SQL執行是否在監聽狀態

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.234
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: zidingyi.000001
          Read_Master_Log_Pos: 1108
               Relay_Log_File: Huaching-2-relay-bin.000002
                Relay_Log_Pos: 319
        Relay_Master_Log_File: zidingyi.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1108
              Relay_Log_Space: 531
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 10
                  Master_UUID: 9174f3d7-9c9a-11e8-88a9-08002733edda
             Master_Info_File: /data/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 

測試主從同步

master和slave的my.cnf中使用的同步配置

master的my.cnf中可以指定同步時排除或者只同步某些庫
#binlog-do-db=db1        #只針對指定庫同步
#binlog-ignore-db=mysql    針對某些庫不同步

slave角色配置針對某些庫完全記錄執行,不會忽略掉binlog中某條SQL執行語句
replicate_wild_do_table=   支持通配符,統配庫,如user.
replicate_wild_ignore_table=   表示這個配置裏的內容會被忽略執行

不建議使用以下的配置參數,因爲匹配同步的庫也有可能會被忽略不去執行
匹配庫
replicate_do_db=
replicate_ignore_db=
匹配表
replicate_do_table=
replicate_ignore_table=

在主上查詢庫的操作,查詢主從數據是否一致,相同的庫、相同的表

mysql> use mysql2
Database changed
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 6        |
+----------+
1 row in set (0.00 sec)

slave從上的查詢結果

mysql> use mysql2
Database changed
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 6        |
+----------+
1 row in set (0.00 sec)

在主上清空這個數據表的內容並查看數據表的行數

mysql> truncate table user;
Query OK, 0 rows affected (0.00 sec)
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 0        |
+----------+
1 row in set (0.00 sec)

slave從上只執行查詢數據錶行數的操作,結果是會把同樣的數據執行同步過來

mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 0        |
+----------+
1 row in set (0.00 sec)

如果發生在從上刪除表刪除庫的操作,此時master主上如果誤執行了slave上被刪除的內容的話,還會造成主從同步發生問題,只能通過重新在slave上指定position的值來進行同步了。這種誤操作會破壞主從之間的同步

從刪除某些內容後再次同步時發生的報錯信息

Last_ SQL_ Error: Error 'Can't drop database 'user'; database doesn't exist' on query. Default database: 'user'.  Query: 'drop database user'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章