1.簡介 MySQL Router是MySQL官方提供的一個輕量級MySQL中間件,用于取代以前老版本的SQL proxy。
既然MySQL Router是一個數據庫的中間件,那么MySQL Router必須能夠分析來自前面客戶端的SQL請求是寫請求還是讀請求,以便決定這個SQL請求是發送給master還是slave,以及發送給哪個master、哪個slave。這樣, MySQL Router就實現了MySQL的讀寫分離,對MySQL請求進行了負載均衡。
因此,MySQL Router的前提是后端實現了MySQL的主從復制。
MySQL Router很輕量級,只能通過不同的端口來實現簡單的讀/寫分離,且讀請求的調度算法只能使用默認的rr(round-robin),更多一點、更復雜一點的能力都不具備。所以,在實現MySQL Router時,需要自行配置好后端MySQL的高可用。高可用建議通過Percona XtraDB Cluster或MariaDB Galera或MySQL官方的group replication實現,如果實在沒有選擇,還可以通過MHA實現。
4[root@s1 mr]# cat /usr/local/mysqlrouter/log/mysqlrouter.log 2018-07-07 10:14:29 INFO [7f8a8e253700] [routing:slaves] started: listening on 192.168.100.21:7001; read-only 2018-07-07 10:14:29 INFO [7f8a8ea54700] [routing:masters] started: listening on 192.168.100.21:7002; read-write 最后進行測試即可。測試前,先在后端Master上授權MySQL Router節點允許連接,它將會復制到兩個slave節點上。
mysql> grant all on *.* to root@'192.168.100.%' identified by 'P@ssword1!'; 連上MySQL Router的7002端口,這個端口是負責寫的端口。由于沒有配置主從高可用,所以,簡單測試下是否能寫即可。
22[root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7002 -e 'select @@server_id;' mysql: [Warning] Using a password on the command line interface can be insecure. +-------------+ | @@server_id | +-------------+ | 110 | +-------------+ [root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7002 -e 'create database mytest;' mysql: [Warning] Using a password on the command line interface can be insecure. [root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7002 -e 'show databases;' mysql: [Warning] Using a password on the command line interface can be insecure. +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | mytest | | performance_schema | | sys | +--------------------+ 再測試下各slave節點,是否能實現rr調度算法的讀請求的負載均衡。
27[root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7001 -e 'select @@server_id;' mysql: [Warning] Using a password on the command line interface can be insecure. +-------------+ | @@server_id | +-------------+ | 120 | +-------------+ [root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7001 -e 'select @@server_id;' mysql: [Warning] Using a password on the command line interface can be insecure. +-------------+ | @@server_id | +-------------+ | 130 | +-------------+ [root@s1 mr]# mysql -uroot -pP@ssword1! -h292.168.100.21 -P7001 -e 'show databases;' mysql: [Warning] Using a password on the command line interface can be insecure. +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | mytest | | performance_schema | | sys | +--------------------+ 顯然,測試的結果一切正常。