mysql 讀寫分離(基礎篇)
更新時間:2009年04月13日 11:10:42 作者:
MySQL Proxy最強大的一項功能是實現(xiàn)“讀寫分離(Read/Write Splitting)”。
基本的原理是讓主數(shù)據(jù)庫處理事務性查詢,而從數(shù)據(jù)庫處理SELECT查詢。數(shù)據(jù)庫復制被用來把事務性查詢導致的變更同步到集群中的從數(shù)據(jù)庫。
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]
-- 需要選擇一個擁有空閑連接的從數(shù)據(jù)庫
if s.type == proxy.BACKEND_TYPE_RO and
s.idling_connections > 0 then
if max_conns == -1 or
s.connected_clients < max_conns then
max_conns = s.connected_clients
max_conns_ndx = i
end
end
end
-- 至此,我們找到了一個擁有空閑連接的從數(shù)據(jù)庫
if max_conns_ndx > 0 then
proxy.connection.backend_ndx = max_conns_ndx
end
else
-- 發(fā)送到主數(shù)據(jù)庫
end
return proxy.PROXY_SEND_QUERY
注釋:此技巧還可以用來實現(xiàn)其他的數(shù)據(jù)分布策略,例如分片(Sharding)。
Jan Kneschke在《MySQL Proxy learns R/W Splitting》中詳細的介紹了這種技巧以及連接池問題:
為了實現(xiàn)讀寫分離我們需要連接池。我們僅在已打開了到一個后端的一條經(jīng)過認證的連接的情況下,才切換到該后端。MySQL協(xié)議首先進行握手。當進入到查詢/返回結(jié)果的階段再認證新連接就太晚了。我們必須保證擁有足夠的打開的連接才能保持運作正常。
實現(xiàn)讀寫分離的LUA腳本:
-- 讀寫分離
--
-- 發(fā)送所有的非事務性Select到一個從數(shù)據(jù)庫
復制代碼 代碼如下:
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]
-- 需要選擇一個擁有空閑連接的從數(shù)據(jù)庫
if s.type == proxy.BACKEND_TYPE_RO and
s.idling_connections > 0 then
if max_conns == -1 or
s.connected_clients < max_conns then
max_conns = s.connected_clients
max_conns_ndx = i
end
end
end
-- 至此,我們找到了一個擁有空閑連接的從數(shù)據(jù)庫
if max_conns_ndx > 0 then
proxy.connection.backend_ndx = max_conns_ndx
end
else
-- 發(fā)送到主數(shù)據(jù)庫
end
return proxy.PROXY_SEND_QUERY
注釋:此技巧還可以用來實現(xiàn)其他的數(shù)據(jù)分布策略,例如分片(Sharding)。
相關文章
Mysql數(shù)據(jù)庫時間與系統(tǒng)時間不一致問題排查及解決
最近忽然發(fā)現(xiàn)個問題,Mysql數(shù)據(jù)庫時間與系統(tǒng)時間不一致,通過查找相關資料終于解決了,下面這篇文章主要給大家介紹了關于Mysql數(shù)據(jù)庫時間與系統(tǒng)時間不一致問題排查及解決的相關資料,需要的朋友可以參考下2023-06-06
Mysql version can not be less than 4.1 出錯解決辦法
這篇文章主要介紹了Mysql version can not be less than 4.1 解決辦法的相關資料,需要的朋友可以參考下2016-10-10

