Linux下MySQL 5.7 主從複製(主從同步)

來源:互聯網
上載者:User

標籤:sch   ali   variables   code   避免   inux   count   vim   Opens   

1、說明:

首先要準備兩台伺服器,一台主伺服器(Master),另一台從伺服器(Slave),然後要保證Master與Slave的版本要相同且Master不能高於Slave的版本,一般穩健的做法都是使其版本相同,因為MySQL不同版本之間的binlog(二進位日誌)格式可能會不一樣,最後會導致同步出現異常。

IP 主機名稱 角色
192.168.1.101 MySQL-001 master
192.168.1.102 MySQL-002 slave
版本:

系統:CentOS 6. 或 7.
MySQL版本:5.7

2、master設定檔設定如下

一般mysql設定檔在/etc/my.cnf

(如果找不到的話也有可能在這些目錄下:/etc/mysql/my.cnf,/usr/local/mysql/etc/my.cnf,~/.my.cnf)

[[email protected] ~]# vim /etc/my.cnf[mysqld]basedir=/usr/local/mysqldatadir=/data/mysqldatasocket=/tmp/mysql.sockuser=mysqlport=3306# master的配置server-id=1             # 伺服器id (主從必須不一樣)binlog-do-db=employees  # 要給從機同步的庫binlog-ignore-db=mysql  # 不給從機同步的庫(多個寫多行)binlog-ignore-db=information_schemabinlog-ignore-db=performance_schemabinlog-ignore-db=syslog-bin=mysql-bin       # 開啟日誌(主機需要開啟),這個mysql-bin也可以自訂;expire_logs_days=90     # 自動清理 90 天前的log檔案,可根據需要修改

重啟資料庫使配置生效:
CentOS 6.*:

[[email protected] ~]# service mysqld restart [[email protected] ~]# service mysqld status SUCCESS! MySQL running (15607)

CentOS 7.*:

[[email protected] ~]# systemctl restart  mysqld.service[[email protected] ~]# systemctl status mysqld.servicemysqld.service - MySQL Server   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled)   Active: active (running) since 四 2018-05-17 11:42:02 CST; 2h 5min ago     Docs: man:mysqld(8)        http://dev.mysql.com/doc/refman/en/using-systemd.html Main PID: 29959 (mysqld)   CGroup: /system.slice/mysqld.service       └─29959 /opt/mysql/bin/mysqld --defaults-file=/etc/my.cnf5月 17 11:42:02 tcloud-118 systemd[1]: Started MySQL Server.

測試log_bin是否成功開啟

[[email protected] ~]# mysql -uroot -pmysql> show variables like ‘%log_bin%‘;+---------------------------------+---------------------------------+| Variable_name                   | Value                           |+---------------------------------+---------------------------------+| log_bin                         | ON                              || log_bin_basename                | /opt/mysql/logs/mysql-bin       || log_bin_index                   | /opt/mysql/logs/mysql-bin.index || log_bin_trust_function_creators | ON                              || log_bin_use_v1_row_events       | OFF                             || sql_log_bin                     | ON                              |+---------------------------------+---------------------------------+6 rows in set (0.00 sec)mysql>

可以看到log_bin為ON;

3、master的資料庫中建立主從同步帳號backup:

backup為使用者名稱,192.168.1.%表示只允許192.168.1網段的用戶端串連,123456為密碼;

mysql> grant replication slave on *.* to ‘backup‘@‘192.168.1.%‘ identified by ‘123456‘;   # 建立同步賬戶mysql> flush privileges;                                                                  # 重新整理許可權mysql> select Host,User,authentication_string from mysql.user;                            # 檢查是否建立+--------------+---------------+-------------------------------------------+| Host         | User          | authentication_string                     |+--------------+---------------+-------------------------------------------+| localhost    | root          | *6C362347EBEAA7DF44F6D34884615A35095E80EB || localhost    | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE || localhost    | mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE || 192.168.1.%  | backup        | *9BB58B7F11A03B83C396FF506F3DF45727E79614 |+--------------+---------------+-------------------------------------------+5 rows in set (0.00 sec)mysql>

[email protected]%賬戶已建立;

4、Master鎖表,往slave拷貝資料

重啟MySQL服務並設定讀取鎖定,讀取鎖定的意思是只能讀取,不能更新,以便獲得一個一致性的快照;

mysql> flush table with read lock;     # 主庫鎖表;預設28800秒,即8小時自動解鎖;mysql> show master status \G*************************** 1. row ***************************             File: mysql-bin.000002         Position: 1621     Binlog_Do_DB: Binlog_Ignore_DB: mysqlExecuted_Gtid_Set: 1d3d078c-59a7-11e8-9a08-00163e000b3f:1-71 row in set (0.00 sec)mysql>

查看主伺服器上當前的二進位日誌名和位移量值這裡的file 和position 要和上面的一致;
匯出master(192.168.1.101)上的資料,然後匯入slave 中

master:
格式:mysqldump -uUSER -pPASSWORD DATABASE TABLE > NAME.sql

[[email protected] ~]# mysqldump -uroot -p employees > /opt/employees.sql    # 假如employees為主庫已經存在的庫[[email protected] ~]# yum install openssh-clients -y                        # 可選[[email protected] ~]# scp /opt/employees.sql [email protected]:/opt/

slave:

[[email protected] ~]# yum install openssh-clients -y                        # 可選
5、配置slave(192.168.1.102)
[[email protected] ~]# vim /etc/my.cnf[mysqld]basedir=/usr/local/mysql    # mysql程式路徑datadir=/data/mysqldata     # mysql資料目錄socket=/tmp/mysql.sockuser=mysqlport=3306# slave配置server-id=2                 # MySQLid 後面2個從伺服器需設定不同skip_slave_start=1          # 複製進程不會隨著資料庫的啟動而啟動,重啟資料庫後需手動啟動;#加上以下參數可以避免更新不及時,SLAVE 重啟後導致的主從複製出錯。read_only = 1               # 從庫普通賬戶唯讀;master_info_repository=TABLErelay_log_info_repository=TABLE#relay_log_recovery=1       # 從機禁止寫#super_read_only=1          # 從機禁止寫

重啟資料庫

CentOS 6.*:

[[email protected] ~]# service mysqld restart [[email protected] ~]# service mysqld status SUCCESS! MySQL running (15604)

CentOS 7.*:

[[email protected] ~]# systemctl restart mysqld.service[[email protected] ~]# systemctl status mysqld.servicemysqld.service - MySQL Server   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled)   Active: active (running) since 四 2018-05-17 11:42:02 CST; 2h 5min ago     Docs: man:mysqld(8)        http://dev.mysql.com/doc/refman/en/using-systemd.html Main PID: 29959 (mysqld)   CGroup: /system.slice/mysqld.service       └─29959 /opt/mysql/bin/mysqld --defaults-file=/etc/my.cnf5月 17 11:42:02 tcloud-118 systemd[1]: Started MySQL Server.

然後匯入到mysql資料庫中,slave上的employees資料庫不存在則先建立,然後再匯入

[[email protected] ~]# mysql -uroot -pmysql> create database employees;        # 建立這個庫[[email protected] ~]# mysql -uroot -p employees < /opt/employees.sql

登入slave資料庫,並做如下設定

[[email protected] ~]# mysql -uroot -pmysql> stop slave;                  # 關閉slave同步,第一次可略過;mysql> change master to-> master_host=‘192.168.1.101‘,     # master的ip-> master_user=‘backup‘,            # 備份使用者名稱-> master_password=‘123456‘,        # 密碼-> master_log_file=‘mysql-bin.000002‘,    # 上面,且要與master的參數一致-> master_log_pos=1621;              # 上面,且要與master的參數一致

合寫為:

mysql> change master to master_host=‘192.168.1.101‘, master_user=‘backup‘, master_password=‘123456‘, master_log_file=‘mysql-bin.000002‘, master_log_pos=1621;mysql> start slave;                 # 啟動同步mysql> show slave status \G         # 查看slave從機的狀態*************************** 1. row ***************************               Slave_IO_State: Waiting for master to send event                  Master_Host: 192.168.1.101                  Master_User: backup                  Master_Port: 3306                Connect_Retry: 60              Master_Log_File: mysql-bin.000002          Read_Master_Log_Pos: 1621               Relay_Log_File: relay-bin.000002                Relay_Log_Pos: 320        Relay_Master_Log_File: mysql-bin.000002             Slave_IO_Running: Yes            Slave_SQL_Running: Yes              Replicate_Do_DB:          Replicate_Ignore_DB: mysql           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: 1621              Relay_Log_Space: 521              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: 0Master_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: 101                  Master_UUID: 1d3d078c-59a7-11e8-9a08-00163e000b3f             Master_Info_File: mysql.slave_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: 5037e479-59a7-11e8-a35b-00163e000402:1-3                Auto_Position: 0         Replicate_Rewrite_DB:                 Channel_Name:           Master_TLS_Version:1 row in set (0.00 sec)mysql>

下面對應參數相同代表設定成功,0延時;

Slave_IO_Running: YesSlave_SQL_Running: YesSeconds_Behind_Master: 0
6、關閉掉主要資料庫的讀取鎖定,並測試
mysql> unlock tables;

在marster中建立一個新表再查看slave中是否有資料

master:

mysql> use employees;mysql> create table test001(id int auto_increment primary key,name varchar(20) not null);mysql> insert into test001 values(null,‘will‘);mysql> insert into test001 values(null,‘jim‘);mysql> insert into test001 values(null,‘tom‘);mysql> select * from employees.test001;+----+------+| id | name |+----+------+|  1 | will ||  2 | jim  ||  3 | tom  |+----+------+3 rows in set (0.01 sec)

slave:

mysql> use employees;mysql> select * from employees.test001;+----+------+| id | name |+----+------+|  1 | will ||  2 | jim  ||  3 | tom  |+----+------+

測試2:重啟關閉從資料庫,主刪除test001表,然後主從資料庫都重啟看是否正常

master:

mysql> drop table employees.test001;

slave:

mysql> use employees;mysql> show tables;

以上實驗證明主從同步成功!!!

Linux下MySQL 5.7 主從複製(主從同步)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.