Linux下MySQL主從複製(GTID)+讀寫分離(ProxySQL)-實施筆記

上古南城發表於2021-08-30

GTID概念:

  • GTID( Global Transaction Identifier)全域性事務標識。GTID 是 5.6 版本引入的一個有關於主從複製的重大改進,相對於之前版本基於 Binlog 檔案 + Position 的主從複製,基於 GTID 的主從複製,資料一致性更高,主從資料複製更健壯,主從切換、故障切換不易出錯,很少需要人為介入處理。
  • GTID是對於一個已提交事務的編號,並且是一個全域性唯一的編號。GTID實際上是由UUID+TID組成的。其中UUID是一個MySQL例項的唯一標識,儲存在mysql資料目錄下的$datadir/auto.cnf檔案裡。TID代表了該例項上已經提交的事務數量,並且隨著事務提交單調遞增。下面是一個GTID的具體形式:3E11FA47-71CA-11E1-9E33-C80AA9429562:23。如果複製結構中,任意兩臺伺服器uuid重複的話(比如直接冷備份時,auto.conf中的內容是一致的),在啟動複製功能的時候會報錯。這時可以刪除auto.conf檔案再重啟mysqld。

GTID的工作原理:

從伺服器連線到主伺服器之後,把自己執行過的GTID (Executed_Gtid_Set: 即已經執行的事務編碼)<SQL執行緒> 、獲取到的GTID (Retrieved_Gtid_Set: 即從庫已經接收到主庫的事務編號) <IO執行緒>發給主伺服器,主伺服器把從伺服器缺少的GTID及對應的transactions發過去補全即可。當主伺服器掛掉的時候,找出同步最成功的那臺從伺服器,直接把它提升為主即可。如果硬要指定某一臺不是最新的從伺服器提升為主, 先change到同步最成功的那臺從伺服器, 等把GTID全部補全了,就可以把它提升為主了。

  簡單概述如下:

  • 1.當一個事務在主庫端執行並提交時,產生GTID,一同記錄到binlog日誌中。
  • 2.binlog傳輸到slave,並儲存到slave的relaylog後,讀取這個GTID的這個值設定gtid_next變數,即告訴Slave,下一個要執行的GTID值。
  • 3.sql執行緒從relay log中獲取GTID,然後對比slave端的binlog是否有該GTID。
  • 4.如果有記錄,說明該GTID的事務已經執行,slave會忽略。
  • 5.如果沒有記錄,slave就會執行該GTID事務,並記錄該GTID到自身的binlog,在讀取執行事務前會先檢查其他session持有該GTID,確保不被重複執行。
  • 6.在解析過程中會判斷是否有主鍵,如果沒有就用二級索引,如果沒有就用全部掃描。

GTID的生命週期:gtid的生命週期對於配置和維護基於gtid的複製至關重要。

  • 1.GTID在主庫提交事務的flush階段產生,但並非所有事務都會產生GTID(如只讀事務)
  • 2.事務拿到GTID後,會生成Gtid_log_event,在提交的時候會記錄到binlog event事務的開頭。
  • 3.在binlog寫滿或者伺服器關閉的時候,伺服器會把這個binlog所有的GTID寫到mysql.gtid_executed表裡進行持久化。
  • 4.當事務提交後,事務會把分配到的Gtid新增到gtid_executed系統變數中。gtid_executed裡面記錄的所有提交的GTID事務,它是實時的。
  • 5.binlog傳送到從庫的relay log中,從庫讀取binlog event裡面的Gtid,並設定自己的gtid_next變數為讀到的gtid值,從庫在進行下一個事務,就會使用這個GTID來提交事務。
  • 6.從庫先會判斷當前是否有執行緒正持有這個Gtid,也會確定這個Gtid對應的事務是否已經執行過了。已經執行的事務會被跳過。gtid_owned專門用來儲存當前正被執行緒持有的Gtid,事務提交成功,也會把Gtid從gtid_owned集合裡釋放。
  • 7.如果從庫開啟了binlog,GTID也會伴隨Gtid_event_log寫到binlog裡,這和主庫的邏輯一樣,在重啟和binlog寫滿的邏輯也一樣。
  • 8.如果從庫沒有開啟binlog,從庫的GTID只能通過gtid_executed表來儲存,每次事務提交,GTID會實時寫入到gtid_executed表中,這個時候gtid_executed變數和gtid_executed表的資料是同步的。

 GTID的優缺點:

  • 優點:
    • 1.保證同一個事務在某slave上絕對只執行一次,沒有執行過的gtid事務總是會被執行。
    • 2.不用像傳統複製那樣保證binlog的座標準確,因為根本不需要binlog以及座標。
    • 3.故障轉移到新的master的時候很方便,簡化了很多工。
    • 4.很容易判斷master和slave的資料是否一致。只要master上提交的事務在slave上也提交了,那麼一定是一致的。
    • 5.當然,MySQL提供了選項可以控制跳過某些gtid事務,防止slave第一次啟動複製時執行master上的所有事務而導致耗時過久。
    • 6.雖然對於row-based和statement-based的格式都能進行gtid複製,但建議採用row-based格式。
  • 缺點:
    • 1.不支援非事務引擎。
    • 2.在一個複製組中,必須要求統一開啟GTID或者是關閉GTID
    • 3.不支援sql_slave_skip_counter(一般用這個來跳過基於binlog主從複製出現的問題)。
    • 4.不允許一個SQL同時更新一個事務引擎表和非事務引擎表。
    • 5.為了保證事務的安全性,create table ... select無法使用。不能使用create temporary table建立臨時表。不能使用關聯更新事務表和非事務表。

MySQL GTID複製部署過程如下。

屬性 主資料庫 從資料庫
節點 Mysql-Master01 Mysql-Slave01
系統 CentOS Linux release 7.5.1804 (Minimal) CentOS Linux release 7.5.1804 (Minimal)
核心 3.10.0-862.el7.x86_64 3.10.0-862.el7.x86_64
SELinux setenforce 0 | disabled setenforce 0 | disabled
Firewlld systemctl stop/disable firewalld systemctl stop/disable firewalld
IP地址 172.16.70.37 172.16.70.181
  • Master01,Slave01相同操作部分,以Master01為例。
# 時間同步
[root@Mysql-Master01 ~]# yum install -y ntp
[root@Mysql-Master01 ~]# systemctl start ntpd && systemctl enable ntpd
[root@Mysql-Master01 ~]# timedatectl set-timezone Asia/Shanghai

# yum安裝MySQL5.7(預設最新版本)
[root@Mysql-Master01 ~]# wget https://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql57-community-release-el7-10.noarch.rpm
[root@Mysql-Master01 ~]# yum localinstall -y mysql57-community-release-el7-10.noarch.rpm
[root@Mysql-Master01 ~]# yum repolist enabled | grep "mysql.*-community.*"
[root@Mysql-Master01 ~]# yum install -y mysql-community-server
[root@Mysql-Master01 ~]# mysql -V
mysql  Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using  EditLine wrapper

# 啟動MySQL
[root@Mysql-Master01 ~]# systemctl start mysqld && systemctl enable
Too few arguments.
[root@Mysql-Master01 ~]# systemctl start mysqld && systemctl enable mysqld
[root@Mysql-Master01 ~]# netstat -nutpl | grep mysql
tcp6       0      0 :::3306                 :::*                    LISTEN      2256/mysqld
[root@Mysql-Master01 ~]# ps -ef | grep mysql
mysql      2256      1  0 12:09 ?        00:00:08 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

# MySQL安全初始化
[root@Mysql-Master01 ~]# grep 'temporary password' /var/log/mysqld.log
2021-08-19T04:08:59.720748Z 1 [Note] A temporary password is generated for root@localhost: .!aTlyih4r2y

[root@Mysql-Master01 ~]# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root:  # 輸入MySQL初始密碼 .!aTlyih4r2y

The existing password for the user account root has expired. Please set a new password.

New password:    # 輸入符合複雜密碼策略的新密碼

Re-enter new password:  # 再次輸入
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.

Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : n    # 上面以已經修改了,無需再修改

 ... skipping.
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y    # 是否刪除匿名使用者
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y  # 是否禁用root遠端登入
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y  # 是否刪除test庫和對test庫的訪問許可權
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y   # 是否重新整理授權表使修改生效
Success.

All done!
  • Master01上的操作。
[root@Mysql-Master01 ~]# hostname -I
172.16.70.37

# 設定master01的my.cnf(必須在[mysqld]配置區域)
[root@Mysql-Master01 ~]# cp /etc/my.cnf /etc/my.cnf_bak
[root@Mysql-Master01 ~]# vim /etc/my.cnf
[mysqld]
......
# 新增以下內容
#GTID
server_id = 37    # master01伺服器唯一ID,一般IP最後一段,主從不能重複
gtid_mode = on    # 開啟gtid模式
enforce_gtid_consistency = on  # 強制gtid一直性,用於保證啟動gitd後事務的安全

#binlog
log_bin = master-bin  # 開啟bin-log,並可指定檔案檔案目錄和字首
log-slave-updates = 1  # 在從伺服器進入主伺服器傳入過來的修改日誌所使用,在Mysql5.7之前主從架構上使用gtid模式的話,必須使用此選項,在Mysql5.7取消了,會增加系統負載
binlog_format = row   # 預設為mixed混合模式,更改為row複製,為了資料一致性,推薦採用row模式
sync-master-info = 1  # 同步master_info,任何事物提交以後都必須要把事務提交以後的二進位制日誌事件的位置對應的檔名稱,記錄到master_info中,下次啟動自動讀取,保證資料無丟失
sync_binlog = 1     # 表示binlog進行FSYNC刷盤,同時dump執行緒會在sync階段後進行binlog傳輸 

#relay log
skip_slave_start = 1  # 跳過slave複製執行緒

# 重啟MySQL
[root@Mysql-Master01 ~]# systemctl restart mysqld

# 登入MySQL
[root@Mysql-Master01 ~]# mysql -p
Enter password:

mysql> show master status;  # 檢視master狀態
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000002 |      154 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> show global variables like '%uuid%';  
+---------------+--------------------------------------+
| Variable_name | Value                                |
+---------------+--------------------------------------+
| server_uuid   | 2e12d559-00a3-11ec-9494-000c29ceb2c0 |
+---------------+--------------------------------------+
1 row in set (0.01 sec)

mysql> show global variables like '%gtid%';    # 檢視gtid功能是否開啟
+----------------------------------+-------+
| Variable_name                    | Value |
+----------------------------------+-------+
| binlog_gtid_simple_recovery      | ON    |
| enforce_gtid_consistency         | ON    |
| gtid_executed                    |       |
| gtid_executed_compression_period | 1000  |
| gtid_mode                        | ON    |
| gtid_owned                       |       |
| gtid_purged                      |       |
| session_track_gtids              | OFF   |
+----------------------------------+-------+
8 rows in set (0.00 sec)

mysql> show global variables like 'server_id';  # 檢視伺服器唯一ID
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 37    |
+---------------+-------+
1 row in set (0.00 sec)

mysql> show global variables like '%log_bin%';    # 檢視binlog日誌是否開啟
+---------------------------------+---------------------------------+
| Variable_name                   | Value                           |
+---------------------------------+---------------------------------+
| log_bin                         | ON                              |
| log_bin_basename                | /var/lib/mysql/master-bin       |
| log_bin_index                   | /var/lib/mysql/master-bin.index |
| log_bin_trust_function_creators | OFF                             |
| log_bin_use_v1_row_events       | OFF                             |
+---------------------------------+---------------------------------+
5 rows in set (0.01 sec)

mysql> GRANT REPLICATION SLAVE ON *.* TO 'backup'@'172.16.%.%' IDENTIFIED BY 'Backup@01';    # 建立backup賬戶並授權slave
Query OK, 0 rows affected, 1 warning (0.00 sec)

語句說明:
(1) replication slave為mysql同步的必須許可權,此處不要授權all許可權
(2) *.* 表示所有庫所有表,也可以指定具體的庫和表進行復制。例如mydb.tb1中,mydb為庫名,tb1為表名
(3) 'backup'@'172.16.%.%' backup為同步賬號。172.16.%.%為授權主機網段,使用了%表示允許整個172.16.0.0網段可以用backup這個使用者訪問資料庫
(4) identified by 'Backup@01';  Backup@01為密碼,實際環境下設定複雜密碼

mysql> flush privileges;    # 重新整理許可權
Query OK, 0 rows affected (0.01 sec)

mysql> select user,host from mysql.user where user='backup';    # 檢視是否存在backup使用者
+--------+------------+
| user   | host       |
+--------+------------+
| backup | 172.16.%.% |
+--------+------------+
1 row in set (0.01 sec)

mysql> show grants for backup@'172.16.%.%';    # 檢視backup使用者授權
+---------------------------------------------------------+
| Grants for backup@172.16.%.%                            |
+---------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO 'backup'@'172.16.%.%' |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> show master status;  # 再次檢視master狀態
+-------------------+----------+--------------+------------------+------------------------------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                        |
+-------------------+----------+--------------+------------------+------------------------------------------+
| master-bin.000002 |      600 |              |                  | 2e12d559-00a3-11ec-9494-000c29ceb2c0:1-2 |
+-------------------+----------+--------------+------------------+------------------------------------------+
1 row in set (0.00 sec)

# 建立測試庫mydb01
mysql> CREATE DATABASE IF NOT EXISTS mydb01;
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO mydb01.tb01 VALUES(1,"zhangsan"),(2,"lisi");
Query OK, 2 rows affected (0.04 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM mydb01.tb01;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
+----+----------+
2 rows in set (0.00 sec)

mysql> flush table with read lock;    # 對主資料庫鎖表只讀,防止匯出資料庫的時候有資料寫入。unlock tables命令解除鎖定
Query OK, 0 rows affected (0.01 sec)

mysql> show variables like '%timeout%';    
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| have_statement_timeout      | YES      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |  # 自動解鎖時間受本引數影響
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 60       |
| wait_timeout                | 28800    |  # 自動解鎖時間受本引數影響
+-----------------------------+----------+
13 rows in set (0.01 sec)

mysql> show master status;  # 鎖表後檢視主庫狀態
+-------------------+----------+--------------+------------------+------------------------------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                        |
+-------------------+----------+--------------+------------------+------------------------------------------+
| master-bin.000002 |     1300 |              |                  | 2e12d559-00a3-11ec-9494-000c29ceb2c0:1-5 |
+-------------------+----------+--------------+------------------+------------------------------------------+
1 row in set (0.00 sec)

# 備份mydb01資料庫,傳送至slave01
[root@Mysql-Master01 ~]# mysqldump --single-transaction --master-data=2 --triggers --routines --databases mydb01 -uroot -p > /root/mydb01.sql
Enter password:

注意:
  mysql5.6使用mysqldump備份時,指定備份的具體庫,使用--database
  mysql5.7使用mysqldump備份時,指定備份的具體庫,使用--databases

[root@Mysql-Master01 ~]# rsync -avz /root/mydb01.sql root@172.16.70.181:/root/
The authenticity of host '172.16.70.181 (172.16.70.181)' can't be established.
ECDSA key fingerprint is SHA256:c/5+RMbf79VeNEzwtdtk9cvRoWIDDRg890ew82Hfj+g.
ECDSA key fingerprint is MD5:41:ce:da:7c:7d:ce:93:ed:6f:c3:1d:81:6d:02:18:3b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.70.181' (ECDSA) to the list of known hosts.
root@172.16.70.181's password:  # slave01伺服器root密碼

#匯出資料完畢後,解鎖主庫
[root@Mysql-Master01 ~]# mysql -p
Enter password:

mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
  • Slave01上的操作。
[root@Mysql-Slave01 ~]# cp /etc/my.cnf /etc/my.cnf_bak
[root@Mysql-Slave01 ~]# vim /etc/my.cnf
[mysqld]
#GTID
server_id = 181    # 差異項
gtid_mode = on
enforce_gtid_consistency = on

#binlog
log_bin = slave-bin  # 差異項
log-slave-updates = 1
binlog_format = row
sync-master-info = 1
sync_binlog = 1

#relay log
skip_slave_start = 1
read_only = on  # 差異項;使從伺服器只能進行讀取操作,此引數對超級使用者無效,並且不會影響從伺服器的複製

# 重啟MySQL
[root@Mysql-Slave01 ~]# systemctl restart mysqld

# 登入MySQL
[root@Mysql-Slave01 ~]# mysql -p
Enter password:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

mysql> source /root/mydb01.sql;

mysql> select * from mydb01.tb01;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
+----+----------+
2 rows in set (0.00 sec)

mysql> show variables like 'server_id';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 181   |
+---------------+-------+
1 row in set (0.01 sec)

mysql> show variables like '%log_bin%';
+---------------------------------+---------------------------------+
| Variable_name                   | Value                           |
+---------------------------------+---------------------------------+
| log_bin                         | ON                              |
| log_bin_basename                | /var/lib/mysql/master-bin       |
| log_bin_index                   | /var/lib/mysql/master-bin.index |
| log_bin_trust_function_creators | OFF                             |
| log_bin_use_v1_row_events       | OFF                             |
| sql_log_bin                     | ON                              |
+---------------------------------+---------------------------------+
6 rows in set (0.00 sec)

# 配置主從同步指令 change master
mysql> stop slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> change master to master_host='172.16.70.37',master_port=3306,master_user='backup',master_password='Backup@01',master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.03 sec)

引數說明:(提示:字串用單引號括起來,數值不用引號,注意內容前後不能有空格。)
  change master to 
  master_host='172.16.70.37'  # master主庫IP
  master_port=3306        # 資料庫埠號        
  master_user='backup'      # master上建立用於複製的使用者
  master_password='Backup@01'  # 複製使用者的密碼
  master_auto_position=1     # gtid複製必須設定此項
-------------------------------------------------------------------------
# 上述操作的原理實際上是把使用者密碼等資訊寫入從庫新的master.info檔案中
[root@Mysql-Slave01 ~]# cat /var/lib/mysql/*.info
25

4
172.16.70.37
backup
Backup@01
3306
60
...
--------------------------------------------------------------------------

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

mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 172.16.70.37
                  Master_User: backup
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000002
          Read_Master_Log_Pos: 1300
               Relay_Log_File: Mysql-Slave01-relay-bin.000002
                Relay_Log_Pos: 417
        Relay_Master_Log_File: master-bin.000002
             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: 1300
              Relay_Log_Space: 632
              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: 37
                  Master_UUID: 2e12d559-00a3-11ec-9494-000c29ceb2c0
             Master_Info_File: /var/lib/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: 2e12d559-00a3-11ec-9494-000c29ceb2c0:1-5    # master主資料庫的GTID
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specifie

如上,當IO和SQL執行緒的狀態均為Yes,則表示主從已實現同步了!(主從同步是否成功,最關鍵的為下面的3項狀態引數)
Slave_IO_Running: Yes,這個時I/O執行緒狀態,I/O執行緒負責從從庫到主庫讀取binlog日誌,並寫入從庫的中繼日誌,狀態為Yes表示I/O執行緒工作正常。
Slave_SQL_Running: Yes,這個是SQL執行緒狀態,SQL執行緒負責讀取中繼日誌(relay-log)中的資料並轉換為SQL語句應用到從資料庫中,狀態為Yes表示I/O執行緒工作正常。
Seconds_Behind_Master:0,這個是複製過程中從庫比主庫延遲的秒數,這個引數極度重要,但企業裡更準確地判斷主從延遲的方法為:在主庫寫時間戳,然後從庫讀取時間戳,和當前資料庫時間進行比較,從而認定是否延遲。

===============================================================================
# 再次回到master01機,檢視master狀態
mysql> show slave hosts;
+-----------+------+------+-----------+--------------------------------------+
| Server_id | Host | Port | Master_id | Slave_UUID                           |
+-----------+------+------+-----------+--------------------------------------+
|       181 |      | 3306 |        37 | 343429c9-00a3-11ec-a6e0-000c29191ffb |
+-----------+------+------+-----------+--------------------------------------+
1 row in set (0.00 sec
  • 測試驗證MySQL主從複製效果。
# 在172.16.70.37(master01)的主資料庫插入新資料
mysql> insert into mydb01.tb01 values(11,"chenqi"),(12,"huangba");
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from mydb01.tb01;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
| 11 | chenqi   |
| 12 | huangba  |
+----+----------+
4 rows in set (0.00 sec)

# 然後到172.16.70.181(slave01)上檢視是否自動同步
mysql> select * from mydb01.tb01;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
| 11 | chenqi   |
| 12 | huangba  |
+----+----------+
4 rows in set (0.00 sec)

至此,MySQL主從複製(GTID)已經實現!

MySqL的讀寫分離器MySql-Proxy

  • MySql Proxy是一個處於MySql Client端和MySql Server端之間的簡單程式,它可以監測、分析或改變它們的通訊。它使用靈活,沒有限制,常見的用途包括:負載平衡、故障分析、查詢過渡和修改等。MySqL Proxy就是這麼一箇中間層代理,簡單地說,MySql Proxy就是一個連線池,負責將前臺應用的連線請求轉發給後臺的資料庫,並且通過使用Lua指令碼,實現複雜的連線控制和過渡,從而實現讀寫分離和負載平衡。
  • 對於應用來說,Mysql Proxy是完全透明的,應用則只是需要連線到MySql Proxy的監聽埠即可。當然,這樣Proxy機器可能成為單點失效,但完全可以使用多個Proxy機器作為冗餘,在應用伺服器的連線池配置中配置多個Proxy的連線引數即可。
  • MySql Proxy更強大的一項功能是實現“讀寫分離”,基本原理是讓主資料庫處理事務性查詢,讓從資料庫處理SELECT查詢,資料複製(Replication)用來把主庫的變更同步到叢集中的從庫上。在生成MySql的M-S結構後,實現讀寫分離,需要使用MySql Proxy。
  • 官方ProxySQL文件:https://proxysql.com/documentation/

Mysql-Proxy讀寫分離部署。

屬性 主資料庫 從資料庫 中介軟體
節點 Mysql-Master01 Mysql-Slave01 Mysql-Proxy01
系統 CentOS Linux release 7.5.1804 (Minimal) CentOS Linux release 7.5.1804 (Minimal) CentOS Linux release 7.5.1804 (Minimal)
核心 3.10.0-862.el7.x86_64 3.10.0-862.el7.x86_64 3.10.0-862.el7.x86_64
SELinux setenforce 0 | disabled setenforce 0 | disabled setenforce 0 | disabled
Firewlld systemctl stop/disable firewalld systemctl stop/disable firewalld systemctl stop/disable firewalld
IP地址 172.16.70.37 172.16.70.181 172.16.70.182
  • 在Mysql-Master01上執行。
# 配置監控後端MySQL節點。(在master主資料節點上建立一個用於監控的使用者名稱(只需在master上建立即可,因為會複製到slave上),這個使用者名稱只需具有USAGE許可權即可)
[root@Mysql-Master01 ~]# mysql -p
Enter password:

mysql> create user monitor@'172.16.70.%' identified by 'Monitor@01';
Query OK, 0 rows affected (0.01 sec)

mysql> grant replication client on *.* to monitor@'172.16.70.%';
Query OK, 0 rows affected (0.01 sec)

mysql> grant all on *.* to root@'172.16.70.%' identified by 'Password@01';
Query OK, 0 rows affected, 1 warning (0.00 sec)

# 配置mysql_users
mysql> grant all on *.* to stnduser@'172.16.70.%' identified by 'Password@01';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> show grants for monitor@'172.16.70.%';
+------------------------------------------------------------+
| Grants for monitor@172.16.70.%                             |
+------------------------------------------------------------+
| GRANT REPLICATION CLIENT ON *.* TO 'monitor'@'172.16.70.%' |
+------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
  • 在Mysql-Proxy01上執行。
# CentOS 新增倉庫(根據需要選擇適合版本,這裡選擇proxysql-2.1.x 版本)
[root@Mysql-Proxy01 ~]# vim /etc/yum.repos.d/proxysql.repo
[proxysql_repo]
name= ProxySQL YUM repository
baseurl=http://repo.proxysql.com/ProxySQL/proxysql-2.1.x/centos/$releasever
gpgcheck=1
gpgkey=http://repo.proxysql.com/ProxySQL/repo_pub_key

# 執行安裝
[root@Mysql-Proxy01 ~]# yum install proxysql -y
[root@Mysql-Proxy01 ~]# proxysql -V
ProxySQL version 2.1.1-40-g1c2b7e4, codename Truls

# 啟動proxsql
[root@Mysql-Proxy01 ~]# systemctl start proxysql && systemctl enable proxysql

# 監聽兩預設埠:6032,6033 
[root@Mysql-Proxy01 ~]# systemctl start proxysql && systemctl enable proxysql
[root@Mysql-Proxy01 ~]# netstat -nutpl | grep proxy
tcp        0      0 0.0.0.0:6032            0.0.0.0:*               LISTEN      2885/proxysql
tcp        0      0 0.0.0.0:6033            0.0.0.0:*               LISTEN      2885/proxysql
[root@Mysql-Proxy01 ~]# ps -ef | grep proxy
proxysql   2884      1  0 Aug23 ?        00:00:00 /usr/bin/proxysql --idle-threads -c /etc/proxysql.cnf
proxysql   2885   2884  0 Aug23 ?        00:06:08 /usr/bin/proxysql --idle-threads -c /etc/proxysql.cnf

# 預設配置檔案/etc/proxysql.cnf
[root@Mysql-Proxy01 ~]# grep -Ev '#|^$' /etc/proxysql.cnf
datadir="/var/lib/proxysql"
admin_variables=
{
    admin_credentials="admin:admin"      # 管理介面預設賬號:密碼(可修改)
    mysql_ifaces="0.0.0.0:6032"        # 客戶端介面埠
}
mysql_variables=
{
    threads=4
    max_connections=2048
    default_query_delay=0
    default_query_timeout=36000000
    have_compress=true
    poll_timeout=2000
    interfaces="0.0.0.0:6033"
    default_schema="information_schema"
    stacksize=1048576
    server_version="5.5.30"
    connect_timeout_server=3000
    monitor_username="monitor"
    monitor_password="monitor"
    monitor_history=600000
    monitor_connect_interval=60000
    monitor_ping_interval=10000
    monitor_read_only_interval=1500
    monitor_read_only_timeout=500
    ping_interval_server_msec=120000
    ping_timeout_server=500
    commands_stats=true
    sessions_sort=true
    connect_retries_on_failure=10
}
mysql_servers =
(
)
mysql_users:
(
)
mysql_query_rules:
(
)
scheduler=
(
)
mysql_replication_hostgroups=
(
)

# 登入管理介面(使用預設憑據)
[root@Mysql-Proxy01 ~]# mysql -uadmin -padmin -P6032 -h127.0.0.1
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.30 (ProxySQL Admin Module)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+-----+---------------+-------------------------------------+
| seq | name          | file                                |
+-----+---------------+-------------------------------------+
| 0   | main          |                                     |
| 2   | disk          | /var/lib/proxysql/proxysql.db       |
| 3   | stats         |                                     |
| 4   | monitor       |                                     |
| 5   | stats_history | /var/lib/proxysql/proxysql_stats.db |
+-----+---------------+-------------------------------------+
5 rows in set (0.00 sec)

mysql> show tables from main;
+----------------------------------------------------+
| tables                                             |
+----------------------------------------------------+
| global_variables                                   |
| mysql_aws_aurora_hostgroups                        |
| mysql_collations                                   |
| mysql_firewall_whitelist_rules                     |
| mysql_firewall_whitelist_sqli_fingerprints         |
| mysql_firewall_whitelist_users                     |
| mysql_galera_hostgroups                            |
| mysql_group_replication_hostgroups                 |
| mysql_query_rules                                  |
| mysql_query_rules_fast_routing                     |
| mysql_replication_hostgroups                       |
| mysql_servers                                      |
| mysql_users                                        |
| proxysql_servers                                   |
| restapi_routes                                     |
| runtime_checksums_values                           |
| runtime_global_variables                           |
| runtime_mysql_aws_aurora_hostgroups                |
| runtime_mysql_firewall_whitelist_rules             |
| runtime_mysql_firewall_whitelist_sqli_fingerprints |
| runtime_mysql_firewall_whitelist_users             |
| runtime_mysql_galera_hostgroups                    |
| runtime_mysql_group_replication_hostgroups         |
| runtime_mysql_query_rules                          |
| runtime_mysql_query_rules_fast_routing             |
| runtime_mysql_replication_hostgroups               |
| runtime_mysql_servers                              |
| runtime_mysql_users                                |
| runtime_proxysql_servers                           |
| runtime_restapi_routes                             |
| runtime_scheduler                                  |
| scheduler                                          |
+----------------------------------------------------+
32 rows in set (0.00 sec)

說明重要欄位含義:
global_variables       設定變數,包括監聽的埠、管理賬號等。
mysql_collations       相關字符集和校驗規則。
mysql_query_rules     定義查詢路由規則。

mysql> show tables from monitor;
+--------------------------------------+
| tables                               |
+--------------------------------------+
| mysql_server_aws_aurora_check_status |
| mysql_server_aws_aurora_failovers    |
| mysql_server_aws_aurora_log          |
| mysql_server_connect_log             |
| mysql_server_galera_log              |
| mysql_server_group_replication_log   |
| mysql_server_ping_log                |
| mysql_server_read_only_log           |
| mysql_server_replication_lag_log     |
+--------------------------------------+
9 rows in set (0.00 sec)

注意:runtime_開頭的是執行時的配置,這些是不能修改的。要修改ProxySQL的配置,需要修改了非runtime_表,修改後必須執行LOAD ... TO RUNTIME
   才能載入到RUNTIME生效,執行save ... to disk才能將配置持久化儲存到磁碟。

# 新增MySQL節點,使用insert語句新增主機到mysql_servers表中,其中:hostgroup_id 1 表示寫組,2表示讀組
mysql> insert into mysql_servers(hostgroup_id,hostname,port) values(1,'172.16.70.37',3306);
Query OK, 1 row affected (0.00 sec)

mysql> insert into mysql_servers(hostgroup_id,hostname,port) values(1,'172.16.70.181',3306);
Query OK, 1 row affected (0.00 sec)

mysql> select * from mysql_servers;   # 檢視insert結果
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
| hostgroup_id | hostname      | port | gtid_port | status | weight | compression | max_connections | max_replication_lag | use_ssl | max_latency_ms | comment |
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
| 1            | 172.16.70.37  | 3306 | 0         | ONLINE | 1      | 0           | 1000            | 0                   | 0       | 0              |         |
| 1            | 172.16.70.181 | 3306 | 0         | ONLINE | 1      | 0           | 1000            | 0                   | 0       | 0              |         |
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
2 rows in set (0.00 sec)

# 監控使用者的憑據新增到 ProxySQL
mysql> update global_variables set variable_value='monitor' where variable_name='mysql-monitor_username';
Query OK, 0 rows affected (0.00 sec)

mysql> update global_variables set variable_value='Monitor@01' where variable_name='mysql-monitor_password';
Query OK, 0 rows affected (0.01 sec)

mysql> select * from global_variables where variable_name like 'mysql-monitor_%';
+--------------------------------------------------------------+----------------+
| variable_name                                                | variable_value |
+--------------------------------------------------------------+----------------+
| mysql-monitor_enabled                                        | true           |
| mysql-monitor_connect_timeout                                | 600            |
| mysql-monitor_ping_max_failures                              | 3              |
| mysql-monitor_ping_timeout                                   | 1000           |
| mysql-monitor_read_only_max_timeout_count                    | 3              |
| mysql-monitor_replication_lag_interval                       | 10000          |
| mysql-monitor_replication_lag_timeout                        | 1000           |
| mysql-monitor_replication_lag_count                          | 1              |
| mysql-monitor_groupreplication_healthcheck_interval          | 5000           |
| mysql-monitor_groupreplication_healthcheck_timeout           | 800            |
| mysql-monitor_groupreplication_healthcheck_max_timeout_count | 3              |
| mysql-monitor_groupreplication_max_transactions_behind_count | 3              |
| mysql-monitor_galera_healthcheck_interval                    | 5000           |
| mysql-monitor_galera_healthcheck_timeout                     | 800            |
| mysql-monitor_galera_healthcheck_max_timeout_count           | 3              |
| mysql-monitor_replication_lag_use_percona_heartbeat          |                |
| mysql-monitor_query_interval                                 | 60000          |
| mysql-monitor_query_timeout                                  | 100            |
| mysql-monitor_slave_lag_when_null                            | 60             |
| mysql-monitor_threads_min                                    | 8              |
| mysql-monitor_threads_max                                    | 128            |
| mysql-monitor_threads_queue_maxsize                          | 128            |
| mysql-monitor_wait_timeout                                   | true           |
| mysql-monitor_writer_is_also_reader                          | true           |
| mysql-monitor_username                                       | monitor        |  # 自定義項
| mysql-monitor_password                                       | Monitor@01     |  # 自定義項
| mysql-monitor_history                                        | 600000         |
| mysql-monitor_connect_interval                               | 60000          |
| mysql-monitor_ping_interval                                  | 10000          |
| mysql-monitor_read_only_interval                             | 1500           |
| mysql-monitor_read_only_timeout                              | 500            |
+--------------------------------------------------------------+----------------+
31 rows in set (0.00 sec)

# 啟用配置,並儲存到磁碟
mysql> load mysql servers to runtime;
Query OK, 0 rows affected (0.00 sec)

mysql> save mysql servers to disk;
Query OK, 0 rows affected (0.06 sec)

# 指定一對 READER 和 WRITER 主機組進行配置(寫組id:1 ; 讀組id:2)
mysql> insert into mysql_replication_hostgroups (writer_hostgroup,reader_hostgroup,comment) values (1,2,'cluster1');
Query OK, 1 row affected (0.00 sec)

mysql> select * from mysql_replication_hostgroups;
+------------------+------------------+------------+----------+
| writer_hostgroup | reader_hostgroup | check_type | comment  |
+------------------+------------------+------------+----------+
| 1                | 2                | read_only  | cluster1 |
+------------------+------------------+------------+----------+
1 row in set (0.00 sec)

mysql> load mysql servers to runtime;
Query OK, 0 rows affected (0.00 sec)

# 後臺健康檢查
mysql> show tables from monitor;
+------------------------------------+
| tables                             |
+------------------------------------+
| mysql_server_connect_log           |
| mysql_server_group_replication_log |
| mysql_server_ping_log              |
| mysql_server_read_only_log         |
| mysql_server_replication_lag_log   |
+------------------------------------+
5 rows in set (0.00 sec)

mysql> select * from monitor.mysql_server_connect_log order by time_start_us desc limit 2;  # 對心跳資訊的監控(connect_log)
+---------------+------+------------------+-------------------------+---------------+
| hostname      | port | time_start_us    | connect_success_time_us | connect_error |
+---------------+------+------------------+-------------------------+---------------+
| 172.16.70.37  | 3306 | 1629795694640282 | 3725                    | NULL          |
| 172.16.70.181 | 3306 | 1629795693592247 | 4307                    | NULL          |
+---------------+------+------------------+-------------------------+---------------+
2 rows in set (0.00 sec)

mysql> select * from monitor.mysql_server_ping_log order by time_start_us desc limit 2;    # 對心跳資訊的監控(ping_log)
+---------------+------+------------------+----------------------+------------+
| hostname      | port | time_start_us    | ping_success_time_us | ping_error |
+---------------+------+------------------+----------------------+------------+
| 172.16.70.181 | 3306 | 1629795783687130 | 1114                 | NULL       |
| 172.16.70.37  | 3306 | 1629795783546617 | 716                  | NULL       |
+---------------+------+------------------+----------------------+------------+
2 rows in set (0.00 sec

mysql> select * from mysql_servers;
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
| hostgroup_id | hostname      | port | gtid_port | status | weight | compression | max_connections | max_replication_lag | use_ssl | max_latency_ms | comment |
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
| 1            | 172.16.70.37  | 3306 | 0         | ONLINE | 1      | 0           | 1000            | 0                   | 0       | 0              |         |
| 2            | 172.16.70.181 | 3306 | 0         | ONLINE | 1      | 0           | 1000            | 0                   | 0       | 0              |         |
+--------------+---------------+------+-----------+--------+--------+-------------+-----------------+---------------------+---------+----------------+---------+
2 rows in set (0.00 sec)

# 配置mysql_users
mysql> insert into mysql_users(username,password,default_hostgroup) values('root','Password@01',1);
Query OK, 1 row affected (0.01 sec)

mysql> insert into mysql_users(username,password,default_hostgroup) values('stnduser','Password@01',1);
Query OK, 1 row affected (0.00 sec)

mysql_users表有不少欄位,最主要的三個欄位為username、password和default_hostgroup:
    username:前端連線ProxySQL,以及ProxySQL將SQL語句路由給MySQL所使用的使用者名稱。
    password:使用者名稱對應的密碼。可以是明文密碼,也可以是hash密碼。如果想使用hash密碼,可以先在某個MySQL節點上執行select password(PASSWORD),然後將加密結果複製到該欄位。
    default_hostgroup:該使用者名稱預設的路由目標。例如,指定root使用者的該欄位值為10時,則使用root使用者傳送的SQL語句預設情況下將路由到hostgroup_id=10組中的某個節點。

mysql> select * from mysql_users\G
*************************** 1. row ***************************
              username: root
              password: Password@01
                active: 1
               use_ssl: 0
     default_hostgroup: 1
        default_schema: NULL
         schema_locked: 0
transaction_persistent: 1
          fast_forward: 0
               backend: 1
              frontend: 1
       max_connections: 10000
            attributes:
               comment:
*************************** 2. row ***************************
              username: stnduser
              password: Password@01
                active: 1
               use_ssl: 0
     default_hostgroup: 1
        default_schema: NULL
         schema_locked: 0
transaction_persistent: 1
          fast_forward: 0
               backend: 1
              frontend: 1
       max_connections: 10000
            attributes:
               comment:
2 rows in set (0.00 sec)


mysql> update mysql_users set transaction_persistent=1 where username='root';
Query OK, 1 row affected (0.00 sec)

mysql> update mysql_users set transaction_persistent=1 where username='stnduser';
Query OK, 1 row affected (0.00 sec)

mysql> load mysql users to runtime;
Query OK, 0 rows affected (0.01 sec)

mysql> save mysql users to disk;
Query OK, 0 rows affected (0.02 sec)

# 測試連線終端,分別使用root使用者和stnduser使用者測試下它們是否能路由到預設的hostgroup_id=1(它是一個寫組)讀、寫資料。
[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1 -e "select @@server_id";  # 這是通過轉發埠6033連線的,連線的是轉發到後端真正的資料庫!
+-------------+
| @@server_id |
+-------------+
|          37 |
+-------------+

[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1 -e "create database proxy_db";  # 遠端Mysql-Master01並建立proxy_db
[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1 -e "show databases like 'proxy_db'";
+---------------------+
| Database (proxy_db) |
+---------------------+
| proxy_db            |
+---------------------+

[root@Mysql-Proxy01 ~]# mysql -ustnduser -pPassword@01 -P6033 -h127.0.0.1 -e "show databases like 'proxy_db'";
+---------------------+
| Database (proxy_db) |
+---------------------+
| proxy_db            |
+---------------------+

# Proxy查詢規則
mysql> show tables from stats;  
+--------------------------------------+
| tables                               |
+--------------------------------------+
| global_variables                     |
| stats_memory_metrics                 |
| stats_mysql_commands_counters        |
| stats_mysql_connection_pool          |
| stats_mysql_connection_pool_reset    |
| stats_mysql_errors                   |
| stats_mysql_errors_reset             |
| stats_mysql_free_connections         |
| stats_mysql_global                   |
| stats_mysql_gtid_executed            |
| stats_mysql_prepared_statements_info |
| stats_mysql_processlist              |
| stats_mysql_query_digest             |
| stats_mysql_query_digest_reset       |
| stats_mysql_query_rules              |
| stats_mysql_users                    |
| stats_proxysql_servers_checksums     |
| stats_proxysql_servers_metrics       |
| stats_proxysql_servers_status        |
+--------------------------------------+
19 rows in set (0.00 sec)

mysql> select * from stats.stats_mysql_connection_pool\G    # 顯示與 MySQL 後端以及連線和總體流量相關的資訊
*************************** 1. row ***************************
        hostgroup: 1
         srv_host: 172.16.70.37
         srv_port: 3306
           status: ONLINE
         ConnUsed: 0
         ConnFree: 1
           ConnOK: 1
          ConnERR: 0
      MaxConnUsed: 1
          Queries: 11
Queries_GTID_sync: 0
  Bytes_data_sent: 258
  Bytes_data_recv: 156
       Latency_us: 1496
*************************** 2. row ***************************
        hostgroup: 2
         srv_host: 172.16.70.181
         srv_port: 3306
           status: ONLINE
         ConnUsed: 0
         ConnFree: 0
           ConnOK: 0
          ConnERR: 0
      MaxConnUsed: 0
          Queries: 0
Queries_GTID_sync: 0
  Bytes_data_sent: 0
  Bytes_data_recv: 0
       Latency_us: 1320
2 rows in set (0.01 sec)

mysql> select * from stats_mysql_commands_counters where total_cnt\G    # 返回有關執行的語句型別和執行時間分佈的詳細資訊
*************************** 1. row ***************************
      Command: CREATE_DATABASE
Total_Time_us: 6514
    Total_cnt: 6
    cnt_100us: 0
    cnt_500us: 1
      cnt_1ms: 2
      cnt_5ms: 3
     cnt_10ms: 0
     cnt_50ms: 0
    cnt_100ms: 0
    cnt_500ms: 0
       cnt_1s: 0
       cnt_5s: 0
      cnt_10s: 0
     cnt_INFs: 0
*************************** 2. row ***************************
      Command: SELECT
Total_Time_us: 2683
    Total_cnt: 13
    cnt_100us: 11
    cnt_500us: 0
      cnt_1ms: 1
      cnt_5ms: 1
     cnt_10ms: 0
     cnt_50ms: 0
    cnt_100ms: 0
    cnt_500ms: 0
       cnt_1s: 0
       cnt_5s: 0
      cnt_10s: 0
     cnt_INFs: 0
*************************** 3. row ***************************
      Command: SHOW
Total_Time_us: 3158
    Total_cnt: 3
    cnt_100us: 0
    cnt_500us: 0
      cnt_1ms: 2
      cnt_5ms: 1
     cnt_10ms: 0
     cnt_50ms: 0
    cnt_100ms: 0
    cnt_500ms: 0
       cnt_1s: 0
       cnt_5s: 0
      cnt_10s: 0
     cnt_INFs: 0
3 rows in set (0.00 sec)

# 插入兩個規則,目的是將select語句分離到hostgroup_id=2的讀組,但由於select語句中有一個特殊語句SELECT...FOR UPDATE它會申請寫鎖,所以應該路由到hostgroup_id=1的寫組。
mysql> insert into mysql_query_rules(rule_id,active,match_digest,destination_hostgroup,apply) VALUES (1,1,'^SELECT.*FOR UPDATE$',1,1), (2,1,'^SELECT',2,1);
Query OK, 2 rows affected (0.01 sec)

說明:
  rule_id        規則的id。規則是按照rule_id的順序進行處理的。
  active        只有該欄位值為1的規則才會載入到runtime資料結構,所以只有這些規則才會被查詢處理模組處理。
  username
  match_digest        使用者名稱篩選,當設定為非NULL值時,只有匹配的使用者建立的連線發出的查詢才會被匹配。
  destination_hostgroup        將匹配到的查詢路由到該主機組。但注意,如果使用者的transaction_persistent=1(見mysql_users表),
                   且該使用者建立的連線開啟了一個事務,則這個事務內的所有語句都將路由到同一主機組,無視匹配規則。
  apply        當設定為1後,當匹配到該規則後,將立即應用該規則,不會再評估其它的規則(注意:應用之後,將不會評估mysql_query_rules_fast_routing中的規則)。


mysql> load mysql query rules to runtime;
Query OK, 0 rows affected (0.00 sec)

mysql> save mysql query rules to disk;
Query OK, 0 rows affected (0.01 sec)

注意: 
  select ... for update規則的rule_id必須要小於普通的select規則的rule_id,因為ProxySQL是根據rule_id的順序進行規則匹配的。

# 再次測試,讀操作是否給hostgroup_id=2的讀組
[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|         181 |
+-------------+

# 再看寫操作
[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1 -e 'start transaction;select @@server_id;commit;select @@server_id;'
+-------------+
| @@server_id |
+-------------+
|          37 |
+-------------+
+-------------+
| @@server_id |
+-------------+
|         181 |
+-------------+


# 測試讀寫分離
[root@Mysql-Proxy01 ~]# mysql -uroot -pPassword@01 -P6033 -h127.0.0.1
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 26
Server version: 5.5.30 (ProxySQL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databses;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb01             |
| mysql              |
| performance_schema |
| proxy_db           |
| sys                |
+--------------------+

# 建立資料
mysql> create table proxy_tb(name varchar(20),age int(4));
Query OK, 0 rows affected (0.03 sec)

mysql> insert into proxy_tb values('zhaojiu','20');
Query OK, 1 row affected (0.01 sec)

# 在proxysql管理端檢視讀寫分離
[root@Mysql-Proxy01 ~]# mysql -uadmin -padmin -P6032 -h127.0.0.1
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 27
Server version: 5.5.30 (ProxySQL Admin Module)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select * from stats_mysql_query_digest;
+-----------+--------------------+----------+----------------+--------------------+---------------------------------------------------+------------+------------+------------+----------+----------+----------+-------------------+---------------+
| hostgroup | schemaname         | username | client_address | digest             | digest_text                                       | count_star | first_seen | last_seen  | sum_time | min_time | max_time | sum_rows_affected | sum_rows_sent |
+-----------+--------------------+----------+----------------+--------------------+---------------------------------------------------+------------+------------+------------+----------+----------+----------+-------------------+---------------+
| 2         | proxy_db           | root     |                | 0x4A754D38BB86DC46 | select * from proxy_tb                            | 1          | 1629875080 | 1629875080 | 689      | 689      | 689      | 0                 | 4             |
| 2         | proxy_db           | root     |                | 0x57D3532A839C8743 | SELECT * FROM `proxy_tb` WHERE ?=?                | 1          | 1629875054 | 1629875054 | 9386     | 9386     | 9386     | 0                 | 0             |
| 1         | information_schema | root     |                | 0xF439051B8ABC188E | insert into proxy_tb values(?,?)                  | 1          | 1629875034 | 1629875034 | 5281     | 5281     | 5281     | 0                 | 0             |
| 2         | information_schema | root     |                | 0x620B328FE9D6D71A | SELECT DATABASE()                                 | 2          | 1629865271 | 1629875054 | 6089     | 2261     | 3828     | 0                 | 2             |
| 1         | proxy_db           | root     |                | 0x59D85BA7DD54E405 | create table proxy_tb(name varchar(?),age int(?)) | 1          | 1629865334 | 1629865334 | 29689    | 29689    | 29689    | 0                 | 0             |
+-----------+--------------------+----------+----------------+--------------------+---------------------------------------------------+------------+------------+------------+----------+----------+----------+-------------------+---------------+
5 rows in set (0.00 sec)

# 從上述結果就可以看出讀寫分離配置是成功的,讀請求是轉發到2組,寫請求轉發到1組

說明:
  hostgroup:查詢將要路由到的目標主機組。如果值為-1,則表示命中了查詢快取,直接從快取取資料返回給客戶端。
  schemaname:當前正在執行的查詢所在的schema名稱。
  username:MySQL客戶端連線到ProxySQL使用的使用者名稱。
  digest:一個十六進位制的hash值,唯一地代表除了引數值部分的查詢語句。
  digest_text:引數化後的SQL語句的文字。注意,如果重寫了SQL語句,則這個欄位是顯示的是重寫後的欄位。換句話說,這個欄位是真正路由到後端,被後端節點執行的語句。
  count_star:該查詢(引數相同、值不同)總共被執行的次數。
  first_seen:unix格式的timestamp時間戳,表示該查詢首次被ProxySQL路由出去的時間點。
  last_seen:unix格式的timestamp時間戳,到目前為止,上一次該查詢被ProxySQL路由出去的時間點。
  sum_time:執行該類查詢所花的總時間(單位微秒)。在想要找出程式中哪部分語句消耗時間最長的語句時非常有用,此外根據這個結果還能提供一個如何提升效能的良好開端。
  min_time, max_time:執行該類查詢的時間範圍。min_time表示的是目前為止執行該類查詢所花的最短時間,max_time則是目前為止,執行該類查詢所花的最長時間,單位都是微秒。

  至此,MySQL主從複製(GTID)+讀寫分離的環境部署已經實現!

 

相關文章