The trunk version of the MySQL Proxy 0.6.0 just learnt about changing backends within running connection. It is now up to lua-script to decide which backend shall be used to send requests too. We wrote a complete tutorial which covers ever
The trunk version of the MySQL Proxy 0.6.0 just learnt about changing backends within running connection. It is now up to lua-script to decide which backend shall be used to send requests too.
We wrote a complete tutorial which covers everything from:
- building and maintaining a connection pool with high and low water marks
- transparent authentication (no extra auth against the proxy)
- deciding on Query Level which backend to use
and implement a transparent read/write splitter which sends all non-transactional Queries to the slaves and the rest to the master.
As the splitting is in the hands of the lua-scripting level you can use the same to implement sharding or other rules to route traffic on statement level.
Connection Pooling
For R/W Splitting we need a connection pooling. We only switch to another backend if we already have a authenticated connection open to that backend.
The MySQL protocol first does a challenge-response handshake. When we enter the query/result stage it is too late to authenticate new connections. We have to make sure that we have enough open connections to operate nicely.
In the keepalive tutorial we spend quite some code on connection management. The whole connect_servers() function is only to create new connections for all pools.
- create one connection to each backend
- create new connections until we reach min-idle-connections
- if the two above conditions are met, use a connection from the pool
Let's take a glimpse at the code:
<code>--- config -- -- connection pool local min_idle_connections = 4 local max_idle_connections = 8 --- -- get a connection to a backend -- -- as long as we don't have enough connections in the pool, create new connections -- function connect_server() -- make sure that we connect to each backend at least ones to -- keep the connections to the servers alive -- -- on read_query we can switch the backends again to another backend local least_idle_conns_ndx = 0 local least_idle_conns = 0 for i = 1, #proxy.servers do local s = proxy.servers[i] if s.state ~= proxy.BACKEND_STATE_DOWN then -- try to connect to each backend once at least if s.idling_connections == 0 then proxy.connection.backend_ndx = i return end -- try to open at least min_idle_connections if least_idle_conns_ndx == 0 or ( s.idling_connections 0 then proxy.connection.backend_ndx = least_idle_conns_ndx end if proxy.connection.backend_ndx > 0 and proxy.servers[proxy.connection.backend_ndx].idling_connections >= min_idle_connections then -- we have 4 idling connections in the pool, that's good enough return proxy.PROXY_IGNORE_RESULT end -- open a new connection end </code>
The real trick is in
<code>--- -- put the authed connection into the connection pool function read_auth_result(packet) -- disconnect from the server proxy.connection.backend_ndx = 0 end </code>
The proxy.connection.backend_ndx = 0 we disconnect us from the current backend (lua starts indexing at index 1, 0 is out of bounds). If a second connection comes in now it can use this authed connection too as it is in the pool, idling.
By setting proxy.connection.backend_ndx
you control which backend is used to send your packets too. A backend is defined as a entry of the proxy.servers
table. Each connection has (zero or) one backend. The backends all have a address, a type (RW or RO) and a state (UP or DOWN).
As we also might have to many open connections in the pool we close them on shutdown again if necessary:
<code>--- -- close the connections if we have enough connections in the pool -- -- @return nil - close connection -- IGNORE_RESULT - store connection in the pool function disconnect_client() if proxy.connection.backend_ndx == 0 then -- currently we don't have a server backend assigned -- -- pick a server which has too many idling connections and close one for i = 1, #proxy.servers do local s = proxy.servers[i] if s.state ~= proxy.BACKEND_STATE_DOWN and s.idling_connections > max_idle_connections then -- try to disconnect a backend proxy.connection.backend_ndx = i return end end end end </code>
We only search for a backend which has to many open idling connections and use it before we enter the default behaviour of disconnect_client: shutdown the server connection. if proxy.connection.backend_ndx == 0 then
is the "we don't have backend associated right now". We already saw this in read_auth_result
.
Read/Write Splitting
That is our maintainance of the pool. connect_server()
adds new auth'ed connections to the pool, disconnect_client()
closes them again. The read/write splitting is part of the query/result cycle:
<code>-- read/write splitting function read_query( packet ) if packet:byte() == proxy.COM_QUIT then -- don't send COM_QUIT to the backend. We manage the connection -- in all aspects. proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = "ignored the COM_QUIT" } return proxy.PROXY_SEND_RESULT end -- as we switch between different connenctions we have to make sure that -- we use always the same DB if packet:byte() == proxy.COM_INIT_DB then -- default_db is connection global default_db = packet:sub(2) end if proxy.connection.backend_ndx == 0 then -- we don't have a backend right now -- -- let's pick a master as a good default for i = 1, #proxy.servers do local s = proxy.servers[i] if s.idling_connections > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.type == proxy.BACKEND_TYPE_RW then proxy.connection.backend_ndx = i break end end end if packet:byte() == proxy.COM_QUERY and default_db then -- how can I know the db of the server connection ? proxy.queries:append(2, string.char(proxy.COM_INIT_DB) .. default_db) end proxy.queries:append(1, packet) </code>
Up to now it is only making sure that we behave nicely:
- don't forward
COM_QUIT
to the backend as he will close the connection on us - intercept the
COM_INIT_DB
to know which DB the client wants to work on. If we switch to another backend we have to make sure the same DB is used.
The read/write splitting is now following a simple rule:
- send all non-transactional SELECTs to a slave
- everything else goes to the master
We are still in read_query()
<code> -- read/write splitting -- -- send all non-transactional SELECTs to a slave if is_in_transaction == 0 and packet:byte() == proxy.COM_QUERY and packet:sub(2, 7) == "SELECT" then local max_conns = -1 local max_conns_ndx = 0 for i = 1, #proxy.servers do local s = proxy.servers[i] -- pick a slave which has some idling connections if s.type == proxy.BACKEND_TYPE_RO and s.idling_connections > 0 then if max_conns == -1 or s.connected_clients 0 then proxy.connection.backend_ndx = max_conns_ndx end else -- send to master end return proxy.PROXY_SEND_QUERY end </code>
If we found a slave host which has a idling connection we pick it. If all slaves are busy or down, we just send the query to the master.
As soon as we don't need this connection anymore give it backend to the pool:
<code>--- -- as long as we are in a transaction keep the connection -- otherwise release it so another client can use it function read_query_result( inj ) local res = assert(inj.resultset) local flags = res.flags if inj.id ~= 1 then -- ignore the result of the USE <default_db> return proxy.PROXY_IGNORE_RESULT end is_in_transaction = flags.in_trans if is_in_transaction == 0 then -- release the backend proxy.connection.backend_ndx = 0 end end </default_db></code>
The MySQL Protocol is nice and offers us a in-transaction-flag. This operates on the state of the transaction and works across all engines. If you want to make sure that several statements go to the same backend, open a transaction with BEGIN. No matter which storage engine you use.
Possible extensions
While we are here in this div of the code think about another use case:
- if the master is down, ban all writing queries and only allow reading selects against the slaves.
It keeps your site up and running even if your master is gone. You only have to handle errors on write-statements and transactions.
Known Problems
We might have a race-condition that idling connection closes before we can use it. In that case we are in trouble right now and will close the connection to the client.
We have to add queuing of connections and awaking them up when the connection becomes available again to handle this later.
Next Steps
Testing, testing, testing.
<code>$ mysql-proxy / --proxy-backend-addresses=10.0.0.1:3306 / --proxy-read-only-backend-addresses=10.0.0.10:3306 / --proxy-read-only-backend-addresses=10.0.0.12:3306 / --proxy-lua-script=examples/tutorial-keepalive.lua </code>
The above code works for my tests, but I don't have any real load. Nor can I create all the error-cases you have in your real-life setups. Please send all your comments, concerns and ideas to the MySQL Proxy forum.
Another upcoming step is externalizing all the load-balancer code and move it into modules to make the code easier to understand and reuseable.

存儲過程是MySQL中的預編譯SQL語句集合,用於提高性能和簡化複雜操作。 1.提高性能:首次編譯後,後續調用無需重新編譯。 2.提高安全性:通過權限控制限制數據表訪問。 3.簡化複雜操作:將多條SQL語句組合,簡化應用層邏輯。

MySQL查詢緩存的工作原理是通過存儲SELECT查詢的結果,當相同查詢再次執行時,直接返回緩存結果。 1)查詢緩存提高數據庫讀取性能,通過哈希值查找緩存結果。 2)配置簡單,在MySQL配置文件中設置query_cache_type和query_cache_size。 3)使用SQL_NO_CACHE關鍵字可以禁用特定查詢的緩存。 4)在高頻更新環境中,查詢緩存可能導致性能瓶頸,需通過監控和調整參數優化使用。

MySQL被廣泛應用於各種項目中的原因包括:1.高性能與可擴展性,支持多種存儲引擎;2.易於使用和維護,配置簡單且工具豐富;3.豐富的生態系統,吸引大量社區和第三方工具支持;4.跨平台支持,適用於多種操作系統。

MySQL數據庫升級的步驟包括:1.備份數據庫,2.停止當前MySQL服務,3.安裝新版本MySQL,4.啟動新版本MySQL服務,5.恢復數據庫。升級過程需注意兼容性問題,並可使用高級工具如PerconaToolkit進行測試和優化。

MySQL備份策略包括邏輯備份、物理備份、增量備份、基於復制的備份和雲備份。 1.邏輯備份使用mysqldump導出數據庫結構和數據,適合小型數據庫和版本遷移。 2.物理備份通過複製數據文件,速度快且全面,但需數據庫一致性。 3.增量備份利用二進制日誌記錄變化,適用於大型數據庫。 4.基於復制的備份通過從服務器備份,減少對生產系統的影響。 5.雲備份如AmazonRDS提供自動化解決方案,但成本和控制需考慮。選擇策略時應考慮數據庫大小、停機容忍度、恢復時間和恢復點目標。

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

在MySQL中優化數據庫模式設計可通過以下步驟提升性能:1.索引優化:在常用查詢列上創建索引,平衡查詢和插入更新的開銷。 2.表結構優化:通過規範化或反規範化減少數據冗餘,提高訪問效率。 3.數據類型選擇:使用合適的數據類型,如INT替代VARCHAR,減少存儲空間。 4.分區和分錶:對於大數據量,使用分區和分錶分散數據,提升查詢和維護效率。

tooptimizemysqlperformance,lofterTheSeSteps:1)inasemproperIndexingTospeedUpqueries,2)使用ExplaintplaintoAnalyzeandoptimizequeryPerformance,3)ActiveServerConfigurationStersLikeTlikeTlikeTlikeIkeLikeIkeIkeLikeIkeLikeIkeLikeIkeLikeNodb_buffer_pool_sizizeandmax_connections,4)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器