Mysql的讀寫分離可以使用MySQL Proxy和Amoeba實現,其實也可以使用MySQL-MMM實現讀寫分離的自動切換。MySQL Proxy有一項強大功能是實現"讀寫分離",基本原理是讓主資料庫處理寫方面事務,讓從庫處理SELECT查詢;Amoeba for MySQL是一款優秀的中介軟體軟體,同樣可以實現讀寫分離,負載均衡等功能。下面重點說下Mysql Proxy:
MySQL Proxy處於客戶端應用程式和MySQL伺服器之間,通過截斷、改變並轉發客戶端和後端資料庫之間的通訊來實現其功能。代理伺服器是和TCP/IP協議打交道, 而要理解MySQL Proxy的工作機制,同樣要清楚MySQL客戶端和伺服器之間的通訊協議,MySQL Protocol 包括認證和查詢兩個基本過程: ................................. 認證過程包括: 1)客戶端向伺服器發起連線請求 2)伺服器向客戶端傳送握手資訊 3)客戶端向伺服器傳送認證請求 4)伺服器向客戶端傳送認證結果 ................................ 如果認證通過,則進入查詢過程: 1)客戶端向伺服器發起查詢請求 2)伺服器向客戶端返回查詢結果 當然,這只是一個粗略的描述,每個過程中傳送的包都是有固定格式的。MySQL Proxy要做的,就是介入協議的各個過程。首先MySQL Proxy以伺服器的身份接受客戶端請求, 根據配置對這些請求進行分析處理,然後以客戶端的身份轉發給相應的後端資料庫伺服器,再接受伺服器的資訊,返回給客戶端。所以MySQL Proxy需要同時實現客戶端和服務 器的協議。由於要對客戶端傳送過來的SQL語句進行分析,還需要包含一個SQL解析器。可以說MySQL Proxy相當於一個輕量級的MySQL了,實際上,MySQL Proxy的admin server 是可以接受SQL來查詢狀態資訊的。 MySQL Proxy通過lua 指令碼來控制連線轉發的機制。主要的函式都是配合MySQL Protocol各個過程的,這一點從函式名上就能看出來: connect_server() read_handshake() read_auth() read_auth_result() read_query() read_query_result() 至於為什麼採用lua 指令碼語言,大概是因為MySQL Proxy中採用了wormhole 儲存引擎 的關係吧,這個蟲洞儲存引擎很有意思,資料的儲存格式就是一段lua指令碼。
Mysql Proxy的原理圖
順便貼下Mysql Proxy的工作拓撲圖
部署MySQL Proxy實現讀寫分離並提高併發負載的操作記錄
0)機器環境
ip地址 角色 主機名 182.48.115.237 master master-node 182.48.115.236 slave1 slave-node1 182.48.115.238 slave2 slave-node2 182.48.115.233 proxy proxy-node 四臺機器都關閉防火牆和selinux 繫結hosts設定(四臺機器都要操作) [root@master-node ~]# vim /etc/hosts ...... 182.48.115.237 master-node 182.48.115.236 slave-node1 182.48.115.238 slave-node2 182.48.115.233 proxy-node
1)Mysql主從複製部署(在三臺mysql節點機上部署,本案例是一主兩從架構)
mysql安裝參考:http://www.cnblogs.com/kevingrace/p/6109679.html mysql主從部署參考:http://www.cnblogs.com/kevingrace/p/6256603.html
2)在proxy機器上安裝mysql-proxy
1)安裝mysql-proxy mysql proxy實現讀寫分離是有lua指令碼實現的 下載地址1:https://downloads.mysql.com/archives/proxy/#downloads 下載地址2: http://ftp.ntu.edu.tw/pub/MySQL/Downloads/MySQL-Proxy/ [root@proxy-node ~]# wget http://ftp.ntu.edu.tw/pub/MySQL/Downloads/MySQL-Proxy/mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz [root@proxy-node ~]# tar -zvxf mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz [root@proxy-node ~]# mv mysql-proxy-0.8.5-linux-el6-x86-64bit /usr/local/mysql-proxy [root@proxy-node ~]# useradd -r mysql-proxy 2)提供服務指令碼 [root@proxy-node ~]# vim /etc/init.d/mysql-proxy #!/bin/bash # # mysql-proxy This script starts and stops the mysql-proxy daemon # # chkconfig: - 78 30 # processname: mysql-proxy # description: mysql-proxy is a proxy daemon for mysql # Source function library. . /etc/rc.d/init.d/functions prog="/usr/local/mysql-proxy/bin/mysql-proxy" # Source networking configuration. if [ -f /etc/sysconfig/network ]; then . /etc/sysconfig/network fi # Check that networking is up. [ ${NETWORKING} = "no" ] && exit 0 # Set default mysql-proxy configuration. ADMIN_USER="admin" ADMIN_PASSWD="admin" ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua" PROXY_OPTIONS="--daemon" PROXY_PID=/var/run/mysql-proxy.pid PROXY_USER="mysql-proxy" # Source mysql-proxy configuration. if [ -f /etc/sysconfig/mysql-proxy ]; then . /etc/sysconfig/mysql-proxy fi RETVAL=0 start() { echo -n $"Starting $prog: " daemon $prog $PROXY_OPTIONS --pid-file=$PROXY_PID --proxy-address="$PROXY_ADDRESS" --user=$PROXY_USER --admin-username="$ADMIN_USER" --admin-lua-script="$ADMIN_LUA_SCRIPT" --admin-password="$ADMIN_PASSWORD" RETVAL=$? echo if [ $RETVAL -eq 0 ]; then touch /var/lock/subsys/mysql-proxy fi } stop() { echo -n $"Stopping $prog: " killproc -p $PROXY_PID -d 3 $prog RETVAL=$? echo if [ $RETVAL -eq 0 ]; then rm -f /var/lock/subsys/mysql-proxy rm -f $PROXY_PID fi } # See how we were called. case "$1" in start) start ;; stop) stop ;; restart) stop start ;; condrestart|try-restart) if status -p $PROXY_PIDFILE $prog >&/dev/null; then stop start fi ;; status) status -p $PROXY_PID $prog ;; *) echo "Usage: $0 {start|stop|restart|reload|status|condrestart|try-restart}" RETVAL=1 ;; esac exit $RETVAL [root@proxy-node ~]# chmod 755 /etc/init.d/mysql-proxy [root@proxy-node ~]# chkconfig --add mysql-proxy 3)為服務指令碼提供配置檔案 [root@proxy-node ~]# vim /etc/sysconfig/mysql-proxy # Options for mysql-proxy ADMIN_USER="admin" ADMIN_PASSWORD="admin" ADMIN_ADDRESS="" ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua" PROXY_ADDRESS="" PROXY_USER="mysql-proxy" PROXY_OPTIONS="--daemon --log-level=info --log-use-syslog --plugins=proxy --plugins=admin --proxy-backend-addresses=182.48.115.237:3306 --proxy-read-only-backend-addresses=182.48.115.236:3306 --proxy-read-only-backend-addresses=182.48.115.238:3306 --proxy-lua-script=/usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua" 配置引數解釋: --daemon:以守護程式模式啟動mysql-proxy --proxy-backend-addresses:後端可讀寫的mysql伺服器的地址和埠 --proxy-read-only-backend-addresses:後端只讀mysql伺服器的地址和埠 --proxy-lua-script:完成mysql代理功能的Lua指令碼 4)提供admin.lua檔案 [root@proxy-node ~]# vim /usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua --[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] function set_error(errmsg) proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = errmsg or "error" } end function read_query(packet) if packet:byte() ~= proxy.COM_QUERY then set_error("[admin] we only handle text-based queries (COM_QUERY)") return proxy.PROXY_SEND_RESULT end local query = packet:sub(2) local rows = { } local fields = { } if query:lower() == "select * from backends" then fields = { { name = "backend_ndx", type = proxy.MYSQL_TYPE_LONG }, { name = "address", type = proxy.MYSQL_TYPE_STRING }, { name = "state", type = proxy.MYSQL_TYPE_STRING }, { name = "type", type = proxy.MYSQL_TYPE_STRING }, { name = "uuid", type = proxy.MYSQL_TYPE_STRING }, { name = "connected_clients", type = proxy.MYSQL_TYPE_LONG }, } for i = 1, #proxy.global.backends do local states = { "unknown", "up", "down" } local types = { "unknown", "rw", "ro" } local b = proxy.global.backends[i] rows[#rows + 1] = { i, b.dst.name, -- configured backend address states[b.state + 1], -- the C-id is pushed down starting at 0 types[b.type + 1], -- the C-id is pushed down starting at 0 b.uuid, -- the MySQL Server's UUID if it is managed b.connected_clients -- currently connected clients } end elseif query:lower() == "select * from help" then fields = { { name = "command", type = proxy.MYSQL_TYPE_STRING }, { name = "description", type = proxy.MYSQL_TYPE_STRING }, } rows[#rows + 1] = { "SELECT * FROM help", "shows this help" } rows[#rows + 1] = { "SELECT * FROM backends", "lists the backends and their state" } else set_error("use 'SELECT * FROM help' to see the supported commands") return proxy.PROXY_SEND_RESULT end proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = fields, rows = rows } } return proxy.PROXY_SEND_RESULT end 5)為了測試更明顯,編輯rw-splitting.lua檔案中的其中2個數值: [root@proxy-node ~]# vim /usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua ......... if not proxy.global.config.rwsplit then proxy.global.config.rwsplit = { min_idle_connections = 1, //修改這個值,預設為4 max_idle_connections = 1, //修改這個值,預設為8 is_debug = false } end ........ 注意: mysql-proxy會檢測客戶端連線,當連線沒有超過min_idle_connections預設值時, 不會進行讀寫分離, 即查詢操作會發生到Master上。 6)啟動mysql-proxy [root@proxy-node ~]# service mysql-proxy start Starting /usr/local/mysql-proxy/bin/mysql-proxy: [ OK ] [root@proxy-node ~]# service mysql-proxy status mysql-proxy (pid 4655) is running... [root@proxy-node ~]# netstat -tunlp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:4041 0.0.0.0:* LISTEN 4655/mysql-proxy tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 4655/mysql-proxy 7)連線測試(在任意一臺遠端客戶機上測試連線) [root@slave-node2 ~]# mysql -uadmin -padmin -h182.48.115.233 --port=4041 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 1 Server version: 5.0.99-agent-admin Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. 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 backends; +-------------+---------------------+---------+------+------+-------------------+ | backend_ndx | address | state | type | uuid | connected_clients | +-------------+---------------------+---------+------+------+-------------------+ | 1 | 182.48.115.237:3306 | unknown | rw | NULL | 0 | | 2 | 182.48.115.236:3306 | unknown | ro | NULL | 0 | | 3 | 182.48.115.238:3306 | unknown | ro | NULL | 0 | +-------------+---------------------+---------+------+------+-------------------+ 3 rows in set (0.00 sec)
3)讀寫分離測試
1)在master-node資料庫上建立proxy使用者,從伺服器也會同步這個操作。 mysql> GRANT ALL ON *.* TO 'wang'@'182.48.115.%' IDENTIFIED BY '123456'; Query OK, 0 rows affected (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) 2)proxy-node機器上使用建立的proxy使用者登陸資料庫,進行資料操作 [root@proxy-node ~]# mysql -uwang -h182.48.115.233 -p123456 ....... mysql> create database huanqiutest; Query OK, 1 row affected (0.00 sec) mysql> use huanqiutest; Database changed mysql> create table haha( id int(5), name varchar(10)); Query OK, 0 rows affected (0.19 sec) mysql> insert into haha values(1,"zhangbao"); Query OK, 1 row affected (0.00 sec) mysql> insert into haha values(11,"shibo"); Query OK, 1 row affected (0.00 sec) mysql> select * from haha; +------+----------+ | id | name | +------+----------+ | 1 | zhangbao | | 11 | shibo | +------+----------+ 2 rows in set (0.01 sec) 注意下面兩點: -> 發現使用proxy使用者登陸資料庫寫入的資料只寫入master主庫,然後再同步到slave從庫。如果將從庫的slave同步功能關閉,則從庫就無法更新資料。 -> 登陸從庫伺服器關閉slave同步功能(stop slave),這時再登陸proxy-noed機器肯定會查詢不出資料(能看到表,但是查詢不出資料) -> 以上兩點真正實現了讀寫分離的效果! 3)檢視狀態,在proxy-node機器上操作,可以看到狀態全部為up: [root@proxy-node bin]# mysql -uadmin -padmin -h182.48.115.233 --port=4041 ....... mysql> SELECT * FROM backends; +-------------+---------------------+---------+------+------+-------------------+ | backend_ndx | address | state | type | uuid | connected_clients | +-------------+---------------------+---------+------+------+-------------------+ | 1 | 182.48.115.237:3306 | up | rw | NULL | 0 | | 2 | 182.48.115.236:3306 | up | ro | NULL | 0 | | 3 | 182.48.115.238:3306 | up | ro | NULL | 0 | +-------------+---------------------+---------+------+------+-------------------+ 3 rows in set (0.00 sec)
讀寫分離,延遲是個大問題,要確保主從同步這一環節不要有延遲。
---------------mysql主從同步延遲原理----------------
-> mysql主從同步原理
主庫針對讀寫操作,順序寫 binlog,從庫單執行緒去主庫讀"寫操作的binlog",從庫取到 binlog在本地原樣執行(隨機寫),來保證主從資料邏輯上一致.
mysql的主從複製都是單執行緒的操作,主庫對所有DDL和DML產生 binlog,binlog是順序寫,所以效率很高,slave的Slave_IO_Running執行緒到主庫取日誌,效率比較高,下一步問題來了,slave的 slave_sql_running執行緒將主庫的 DDL和DML操作在 slave實施。DML,DDL的IO操作是隨即的,不能順序的,成本高很多,還有可能slave上的其他查詢產生 lock,由於 slave_sql_running也是單執行緒的,所以 一個 DDL卡住了,需求需求執行一段時間,那麼所有之後的DDL會等待這個 DDL執行完才會繼續執行,這就導致了延遲.由於master可以併發,Slave_sql_running執行緒卻不可以,所以主庫執行 DDL需求一段時間,在slave執行相同的DDL時,就產生了延遲.
-> 主從同步延遲產生原因
當主庫的TPS併發較高時,產生的DDL數量超過Slave一個 sql執行緒所能承受的範圍,那麼延遲就產生了,當然還有就是可能與 slave的大型 query語句產生了鎖等待
首要原因:資料庫在業務上讀寫壓力太大,CPU計算負荷大,網路卡負荷大,硬碟隨機IO太高
次要原因:讀寫 binlog帶來的效能影響,網路傳輸延遲
-> mysql主從同步加速
1)sync_binlog在slave端設定為0
2)–logs-slave-updates 從伺服器從主伺服器接收到的更新不記入它的二進位制日誌。
3)直接禁用slave端的binlog
4)slave端,如果使用的儲存引擎是innodb,innodb_flush_log_at_trx_commit =2
再有就是進行分庫分表處理,這樣減少資料量的複製同步操作