Mysql的讀寫分離可使用MySQL Proxy和Amoeba實現,其實也可使用MySQL-MMM實現讀寫分離的自動切換。MySQL Proxy有一項強大功能是實現"讀寫分離",基本原理是讓主數據庫處理寫方面事務,讓從庫處理SELECT查詢;Amoeba for MySQL是一款優秀的中間件軟件,一樣能夠實現讀寫分離,負載均衡等功能。下面重點說下Mysql Proxy:html
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的原理圖node
順便貼下Mysql Proxy的工做拓撲圖mysql
部署MySQL Proxy實現讀寫分離並提升併發負載的操做記錄linux
0)機器環境redis
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節點機上部署,本案例是一主兩從架構)sql
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)讀寫分離測試vim
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帶來的性能影響,網絡傳輸延遲bash
-> mysql主從同步加速
1)sync_binlog在slave端設置爲0
2)–logs-slave-updates 從服務器從主服務器接收到的更新不記入它的二進制日誌。
3)直接禁用slave端的binlog
4)slave端,若是使用的存儲引擎是innodb,innodb_flush_log_at_trx_commit =2
再有就是進行分庫分表處理,這樣減小數據量的複製同步操做