亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Discuz!NT數(shù)據(jù)庫(kù)讀寫(xiě)分離方案詳解

 更新時(shí)間:2010年06月21日 16:15:03   作者:  
Discuz!NT這個(gè)產(chǎn)品在其企業(yè)版中提供了對(duì)‘讀寫(xiě)分離’機(jī)制的支持,使對(duì)CPU及內(nèi)存消耗嚴(yán)重的操作(CUD)被 分離到一臺(tái)或幾臺(tái)性能很高的機(jī)器上,而將頻繁讀取的操作(select)放到幾臺(tái)配置較低的機(jī)器上,然后通過(guò)‘事務(wù) 發(fā)布訂閱機(jī)制’,實(shí)現(xiàn)了在多個(gè)sqlserver數(shù)據(jù)庫(kù)之間快速高效同步數(shù)據(jù),從而達(dá)到了將‘讀寫(xiě)請(qǐng)求’按實(shí)際負(fù)載 情況進(jìn)行均衡分布的效果。
目前在Discuz!NT這個(gè)產(chǎn)品中,數(shù)據(jù)庫(kù)作為數(shù)據(jù)持久化工具,必定在并發(fā)訪問(wèn)頻繁且負(fù)載壓力較大的情況下成 為系統(tǒng)性能的‘瓶頸'。即使使用本地緩存等方式來(lái)解決頻繁訪問(wèn)數(shù)據(jù)庫(kù)的問(wèn)題,但仍舊會(huì)有大量的并發(fā)請(qǐng)求要訪問(wèn)動(dòng)態(tài)數(shù)據(jù),雖然 SQL2005及2008以上版本中性能不斷提升,查詢(xún)計(jì)劃和存儲(chǔ)過(guò)程運(yùn)行得越來(lái)越高效,但最終還是 要面臨‘瓶頸'這一問(wèn) 題。當(dāng)然這也是許多大型網(wǎng)站不斷研究探索各式各樣的方案來(lái)有效降低數(shù)據(jù)訪問(wèn)負(fù)荷的原 因, 其中的‘讀寫(xiě)分離'方案就是一種被廣泛采用的方案。
      Discuz!NT這個(gè)產(chǎn)品在其企業(yè)版中提供了對(duì)‘讀寫(xiě)分離'機(jī)制的支持,使對(duì)CPU及內(nèi)存消耗嚴(yán)重的操作(CUD)被 分離到一臺(tái)或幾臺(tái)性能很高的機(jī)器上,而將頻繁讀取的操作(select)放到幾臺(tái)配置較低的機(jī)器上,然后通過(guò)‘事務(wù) 發(fā)布訂閱機(jī)制',實(shí)現(xiàn)了在多個(gè)sqlserver數(shù)據(jù)庫(kù)之間快速高效同步數(shù)據(jù),從而達(dá)到了將‘讀寫(xiě)請(qǐng)求'按實(shí)際負(fù)載 情況進(jìn)行均衡分布的效果。

      下面就簡(jiǎn)要介紹一下其實(shí)現(xiàn)思路。注:有關(guān)數(shù)據(jù)同步的工具已在sqlserver中自帶了,可以參考這篇文章

      將相應(yīng)的數(shù)據(jù)由Master(主)數(shù)據(jù)庫(kù)中‘發(fā)布'出來(lái),然后使用推送的方式(注:事務(wù)發(fā)布可以指定是‘通過(guò)主 數(shù)據(jù)庫(kù)推送' 還是‘訂閱服務(wù)器去獲取')發(fā)送到訂閱它的數(shù)據(jù)庫(kù)中,就實(shí)現(xiàn)了數(shù)據(jù)同步功能。

      下面就介紹一下如何通過(guò)改變既有代碼來(lái)實(shí)現(xiàn)在‘幾個(gè)從數(shù)據(jù)庫(kù)(類(lèi)似快照)'間進(jìn)行讀取數(shù)據(jù)的負(fù)載均衡。

      原有的代碼中因?yàn)槭褂昧朔謱訖C(jī)制,所以我們只要在‘?dāng)?shù)據(jù)訪問(wèn)層'動(dòng)一下心思就可以了。在這里我的一個(gè)設(shè) 計(jì)思路就是不改變已有的數(shù)據(jù)庫(kù)訪問(wèn)接口(包括參數(shù)等)的前提下,實(shí)現(xiàn)底層自動(dòng)將現(xiàn)有的數(shù)據(jù)訪問(wèn)操作進(jìn)行負(fù)載 均衡。這樣做的好處不用多說(shuō)了,同時(shí)也讓這個(gè)負(fù)載均衡功能與數(shù)據(jù)訪問(wèn)層相分離,不要耦合的太緊密,同時(shí)如果不曉得底層 的實(shí)現(xiàn)原理也可以只通過(guò)一個(gè)開(kāi)關(guān)(后面會(huì)介紹),就可以讓自己的sql語(yǔ)句自動(dòng)實(shí)現(xiàn)動(dòng)態(tài)負(fù)載均衡。

      說(shuō)到這里,我來(lái)對(duì)照代碼進(jìn)一步闡述:

      首先就是(Discuz.Data\DbHelper.cs)代碼,主要變動(dòng)如下(新增方法部分):   
復(fù)制代碼 代碼如下:

/// <summary>
/// 獲取使用的數(shù)據(jù)庫(kù)(或快照)鏈接串
/// </summary>
/// <param name="commandText">存儲(chǔ)過(guò)程名或都SQL命令文本</param>
/// <returns></returns>
public static string GetRealConnectionString(string commandText)
{
if (DbSnapConfigs.GetConfig() != null && DbSnapConfigs.GetConfig().AppDbSnap)
{
commandText = commandText.Trim().ToLower();
if (commandText.StartsWith("select") || ((commandText.StartsWith(BaseConfigs.GetTablePrefix) && UserSnapDatabase(commandText))))
{
DbSnapInfo dbSnapInfo = GetLoadBalanceScheduling.GetConnectDbSnap();
if (DbSnapConfigs.GetConfig().RecordeLog && snapLogList.Capacity > snapLogList.Count)
snapLogList.Add(string.Format("{{'SouceID' : {0}, 'DbconnectString' : '{1}', 'CommandText' : '{2}', 'PostDateTime' : '{3}'}},",
dbSnapInfo.SouceID,
dbSnapInfo.DbconnectString,
commandText.Replace("'",""),
Discuz.Common.Utils.GetDateTime()));
return dbSnapInfo.DbconnectString;
}
}
return ConnectionString;
}

上面的方法將會(huì)對(duì)傳入的sql語(yǔ)句進(jìn)行分析,找出其中是CUD操作還是SELECT操作,來(lái)區(qū)別是讀還是寫(xiě)操作。而snapLogList列表則是之前所配置的‘事務(wù)發(fā)布訂閱'模式下的相關(guān)‘從數(shù)據(jù)庫(kù)'(Slave Database)鏈接串的列表,例如(dbsnap.config文件的DbSnapInfoList節(jié)點(diǎn)):
復(fù)制代碼 代碼如下:

<?xml version="1.0"?>
<DbSnapAppConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AppDbSnap>true</AppDbSnap>
<WriteWaitTime>1</WriteWaitTime>
<LoadBalanceScheduling>RoundRobinScheduling</LoadBalanceScheduling> --WeightedRoundRobinScheduling
<RecordeLog>false</RecordeLog>
<DbSnapInfoList>
<DbSnapInfo>
<SouceID>1</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ\DNT_DAIZHJ;User ID=sa;Password=123123;Initial Catalog=dnt_snap;Pooling=true</DbconnectString>
<Weight>4</Weight>
</DbSnapInfo>
<DbSnapInfo>
<SouceID>2</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ-PC\2222;User ID=sa;Password=123;Initial Catalog=tabletest;Pooling=true</DbconnectString>
<Weight>3</Weight>
</DbSnapInfo>
</DbSnapInfoList>
</DbSnapAppConfig>

有關(guān)相應(yīng)配置節(jié)點(diǎn)和負(fù)載均衡算法會(huì)在后面提到,這里為了保持文章內(nèi)容的連續(xù)性暫且跳過(guò),下面接著瀏覽一下上面調(diào)用的‘UserSnapDatabase'方法:
復(fù)制代碼 代碼如下:

/// <summary>
/// 是否使用快照數(shù)據(jù)庫(kù)
/// </summary>
/// <param name="commandText">查詢(xún)</param>
/// <returns></returns>
private static bool UserSnapDatabase(string commandText)
{
// 如果上次刷新cookie間隔小于5分鐘, 則不刷新數(shù)據(jù)庫(kù)最后活動(dòng)時(shí)間
if (commandText.StartsWith(BaseConfigs.GetTablePrefix + "create"))
{
Utils.WriteCookie("JumpAfterWrite", Environment.TickCount.ToString());
return false;
}
else if (!String.IsNullOrEmpty(Utils.GetCookie("JumpAfterWrite")) && (Environment.TickCount - TypeConverter.StrToInt(Utils.GetCookie("JumpAfterWrite"), Environment.TickCount)) < DbSnapConfigs.GetConfig().WriteWaitTime * 1000)
return false;
else if (!commandText.StartsWith(BaseConfigs.GetTablePrefix + "get"))
return false;
return true;
}

該方法的作用很簡(jiǎn)單,就是當(dāng)數(shù)據(jù)庫(kù)有CUD操作時(shí),通過(guò)寫(xiě)cookie的方式向客戶(hù)端寫(xiě)一個(gè)鍵值‘JumpAfterWrite',這個(gè)鍵值很重要,就是提供一個(gè)標(biāo)簽(flag)來(lái)指示:‘當(dāng)前用戶(hù)執(zhí)行cud操作時(shí),頁(yè)面跳轉(zhuǎn)到其它頁(yè)面而主數(shù)據(jù)庫(kù)還沒(méi)來(lái)得及將數(shù)據(jù)推送到從數(shù)據(jù)庫(kù)'這一情況而造成的‘?dāng)?shù)據(jù)不同步'問(wèn)題。
舉了例子,當(dāng)在一個(gè)版塊中‘發(fā)表主題'后系統(tǒng)自動(dòng)跳轉(zhuǎn)到‘顯示該主題頁(yè)面'時(shí),如果主數(shù)據(jù)庫(kù)中插入了一個(gè)新主題而從數(shù)據(jù)庫(kù)沒(méi)有被及時(shí)更新這一主題信息時(shí),就會(huì)報(bào)‘主題不存在'這個(gè)錯(cuò)誤。所以這里加了一個(gè)設(shè)置,就是下面這一行:
復(fù)制代碼 代碼如下:

(Environment.TickCount - TypeConverter.StrToInt(Utils.GetCookie("JumpAfterWrite"), Environment.TickCount)) < DbSnapConfigs.GetConfig().WriteWaitTime * 1000)

它所做的就是確保用戶(hù)cud操作之后,在規(guī)定的時(shí)間內(nèi)還是訪問(wèn)主數(shù)據(jù)庫(kù),當(dāng)時(shí)間超過(guò)時(shí),才將當(dāng)前用戶(hù)的訪問(wèn)請(qǐng)求(select)均衡到其它從數(shù)據(jù)庫(kù)中。
當(dāng)然,在GetRealConnectionString()方法中,還有一行代碼很重要,就是下面這一行:
復(fù)制代碼 代碼如下:

DbSnapInfo dbSnapInfo = GetLoadBalanceScheduling.GetConnectDbSnap();


它的作用就是加載配置文件信息,其中最主要的就是相應(yīng)的‘負(fù)載均衡算法實(shí)例'來(lái)獲取相應(yīng)的從數(shù)據(jù)庫(kù)鏈接串,下面先看一
下‘靜態(tài)屬性'GetLoadBalanceScheduling的相關(guān)信息:

代碼
復(fù)制代碼 代碼如下:

/// <summary>
/// 負(fù)載均衡調(diào)度接口
/// </summary>
private static ILoadBalanceScheduling m_loadBalanceSche;
/// <summary>
/// 初始化負(fù)載均衡調(diào)度接口實(shí)例
/// </summary>
private static ILoadBalanceScheduling GetLoadBalanceScheduling
{
get
{
if (m_loadBalanceSche == null)
{
try
{
m_loadBalanceSche = (ILoadBalanceScheduling)Activator.CreateInstance(Type.GetType(string.Format("Discuz.EntLib.{0}, Discuz.EntLib", DbSnapConfigs.GetConfig().LoadBalanceScheduling), false, true));
}
catch
{
throw new Exception("請(qǐng)檢查config/dbsnap.config中配置是否正確");
}
}
return m_loadBalanceSche;
}
}

它主要是通過(guò)反射的方法將Discuz.EntLib.dll文件中的相應(yīng)負(fù)載均衡算法實(shí)例進(jìn)行綁定,然后以m_loadBalanceSche這個(gè)靜態(tài)變量進(jìn)行保存,而m_loadBalanceSche本身就是ILoadBalanceScheduling接口變量,該接口即是相應(yīng)負(fù)載均衡算法的實(shí)現(xiàn)接口。同樣因?yàn)槲恼聝?nèi)容的連續(xù)性,這里先不深挖相應(yīng)的實(shí)現(xiàn)算法,我會(huì)在后面進(jìn)行介紹。下面再來(lái)看一下GetRealConnectionString()中還有一段代碼,如下:
代碼
復(fù)制代碼 代碼如下:

if (DbSnapConfigs.GetConfig().RecordeLog && snapLogList.Capacity > snapLogList.Count)
snapLogList.Add(string.Format("{{'SouceID' : {0}, 'DbconnectString' : '{1}', 'CommandText' : '{2}', 'PostDateTime' : '{3}'}},",
dbSnapInfo.SouceID,
dbSnapInfo.DbconnectString,
commandText.Replace("'",""),
Discuz.Common.Utils.GetDateTime()));
return dbSnapInfo.DbconnectString;

上面代碼將當(dāng)前的負(fù)載均衡得到的鏈接串保存到一個(gè)snapLogList列表中,該列表聲明如下:
復(fù)制代碼 代碼如下:

List<string> snapLogList = new List<string>(400)

為什么要提供這個(gè)列表并進(jìn)行記錄?主要是為了考查負(fù)載均衡算法的工作情況,因?yàn)樵跀?shù)據(jù)訪問(wèn)層獲取相應(yīng)鏈接串信息并進(jìn)行記錄很不方便,所以我用這個(gè)變量記錄大約400條‘負(fù)載均衡'數(shù)據(jù)鏈接串,以便在相應(yīng)的Discuz.EntLib.ToolKit工具包中進(jìn)行觀察,監(jiān)視其‘工作情況'。這里我們只要知道通過(guò)GetRealConnectionString()方法就實(shí)現(xiàn)了對(duì)sql語(yǔ)句或存儲(chǔ)過(guò)程進(jìn)行分析并進(jìn)行負(fù)載均衡的效果了(注:該操作可能會(huì)耗時(shí),所以在DbSnapConfigs中提供了一個(gè)開(kāi)關(guān)‘RecordeLog'來(lái)進(jìn)行控制,后面會(huì)介紹)。

下面再來(lái)簡(jiǎn)單介紹一下,如何改造DbHelper.cs中原有方法,使其支持負(fù)載均衡功能。這里強(qiáng)調(diào)一點(diǎn),就是:
GetRealConnectionString()方法只是造了一個(gè)房子,里面的家具還是要自己搬。
而家具就是那些老的方法,比如:

代碼
復(fù)制代碼 代碼如下:

public static object ExecuteScalar(DbConnection connection, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
//connection.Close();
connection.ConnectionString = GetRealConnectionString(commandText);//負(fù)載均衡改造完成的方法
connection.Open();
// 創(chuàng)建DbCommand命令,并進(jìn)行預(yù)處理
DbCommand cmd = Factory.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
// 執(zhí)行DbCommand命令,并返回結(jié)果.
object retval = cmd.ExecuteScalar();
// 清除參數(shù),以便再次使用.
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}

上面的 ‘connection.ConnectionString ='之前綁定的ConnectionString這個(gè)靜態(tài)屬性,而這個(gè)屬性鏈接的就是‘主數(shù)據(jù)庫(kù)',
這里我們只要將GetRealConnectionString(commandText)賦值給它就可以了,還是那句話(huà),在GetRealConnectionString()就實(shí)現(xiàn)了
數(shù)據(jù)庫(kù)鏈接串的負(fù)載均衡,呵呵。類(lèi)似上面的變動(dòng)在DbHelper.cs還有幾處,好在變化不太大,當(dāng)然更不需要改變?cè)械臄?shù)據(jù)訪問(wèn)層
(比如IDataProvider.cs文件)了。
其實(shí)本文中介紹的數(shù)據(jù)庫(kù)層負(fù)載均衡實(shí)現(xiàn)方法在MYSQL中早有相應(yīng)的插件實(shí)現(xiàn)了,參見(jiàn)這篇文章。      

該文章中的LUA腳本實(shí)現(xiàn)方式與本文類(lèi)似,如下:
--發(fā)送所有的非事務(wù)性SELECT到一個(gè)從數(shù)據(jù)庫(kù)
復(fù)制代碼 代碼如下:

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]
-- 選擇一個(gè)擁有空閑連接的從數(shù)據(jù)庫(kù)
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
.....

接著,我再介紹一下相應(yīng)的配置文件和負(fù)載均衡算法的實(shí)現(xiàn)情況:)
配置文件(比如:Discuz.EntLib.ToolKit\config\dbsnap.config):
代碼
復(fù)制代碼 代碼如下:

<?xml version="1.0"?>
<DbSnapAppConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AppDbSnap>true</AppDbSnap>
<WriteWaitTime>1</WriteWaitTime>
<LoadBalanceScheduling>RoundRobinScheduling</LoadBalanceScheduling> --WeightedRoundRobinScheduling
<RecordeLog>false</RecordeLog>
<DbSnapInfoList>
<DbSnapInfo>
<SouceID>1</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ\DNT_DAIZHJ;User ID=sa;Password=123123;Initial Catalog=dnt_snap;Pooling=true</DbconnectString>
<Weight>4</Weight>
</DbSnapInfo>
<DbSnapInfo>
<SouceID>2</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ-PC\2222;User ID=sa;Password=123;Initial Catalog=tabletest;Pooling=true</DbconnectString>
<Weight>3</Weight>
</DbSnapInfo>
<DbSnapInfo>
<SouceID>3</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ-PC\333333;User ID=sa;Password=123;Initial Catalog=tabletest;Pooling=true</DbconnectString>
<Weight>2</Weight>
</DbSnapInfo>
<DbSnapInfo>
<SouceID>4</SouceID>
<Enable>true</Enable>
<DbconnectString>Data Source=DAIZHJ-PC\44444444;User ID=sa;Password=123;Initial Catalog=tabletest;Pooling=true</DbconnectString>
<Weight>2</Weight>
</DbSnapInfo>
</DbSnapInfoList>
</DbSnapAppConfig>

上面的DbSnapInfoList就是相應(yīng)的slave數(shù)據(jù)庫(kù)鏈接列表,其中它的相應(yīng)節(jié)點(diǎn)信息說(shuō)明如下(Discuz.Config\DbSnapInfo.cs):
代碼
復(fù)制代碼 代碼如下:

[Serializable]
public class DbSnapInfo
{
/// <summary>
/// 源ID,用于唯一標(biāo)識(shí)快照在數(shù)據(jù)庫(kù)負(fù)載均衡中的信息
/// </summary>
private int _souceID;
/// <summary>
/// 源ID,用于唯一標(biāo)識(shí)快照在數(shù)據(jù)庫(kù)負(fù)載均衡中的信息
/// </summary>
public int SouceID
{
get { return _souceID; }
set { _souceID = value; }
}
/// <summary>
/// 快照是否有效
/// </summary>
private bool _enable;
/// <summary>
/// 是否有效
/// </summary>
public bool Enable
{
get { return _enable; }
set { _enable = value; }
}
/// <summary>
/// 快照鏈接
/// </summary>
private string _dbConnectString;
/// <summary>
/// 快照鏈接
/// </summary>
public string DbconnectString
{
get { return _dbConnectString; }
set { _dbConnectString = value; }
}
/// <summary>
/// 權(quán)重信息,該值越高則意味著被輪循到的次數(shù)越多
/// </summary>
private int _weight;
/// <summary>
/// 權(quán)重信息,該值越高則意味著被輪循到的次數(shù)越多
/// </summary>
public int Weight
{
get { return _weight; }
set { _weight = value; }
}
}

當(dāng)然DbSnapAppConfig作為DbSnapInfo列表的容器,其結(jié)構(gòu)如下:
代碼
復(fù)制代碼 代碼如下:

[Serializable]
public class DbSnapAppConfig : Discuz.Config.IConfigInfo
{
private bool _appDbSnap;
/// <summary>
/// 是否啟用快照,如不使用,則即使DbSnapInfoList已設(shè)置有效快照信息也不會(huì)使用。
/// </summary>
public bool AppDbSnap
{
get { return _appDbSnap; }
set { _appDbSnap = value; }
}
private int _writeWaitTime = 6;
/// <summary>
/// 寫(xiě)操作等待時(shí)間(單位:秒), 說(shuō)明:在執(zhí)行完寫(xiě)操作之后,在該時(shí)間內(nèi)的sql請(qǐng)求依舊會(huì)被發(fā)往master數(shù)據(jù)庫(kù)
/// </summary>
public int WriteWaitTime
{
get { return _writeWaitTime; }
set { _writeWaitTime = value; }
}
private string _loadBalanceScheduling = "WeightedRoundRobinScheduling";
/// <summary>
/// 負(fù)載均衡調(diào)度算法,默認(rèn)為權(quán)重輪詢(xún)調(diào)度算法 http://www.pcjx.com/Cisco/zhong/209068.html
/// </summary>
public string LoadBalanceScheduling
{
get { return _loadBalanceScheduling; }
set { _loadBalanceScheduling = value; }
}
private bool _recordeLog = false;
/// <summary>
/// 是否記錄日志
/// </summary>
public bool RecordeLog
{
get { return _recordeLog; }
set { _recordeLog = value; }
}
private List<DbSnapInfo> _dbSnapInfoList;
/// <summary>
/// 快照輪循列表
/// </summary>
public List<DbSnapInfo> DbSnapInfoList
{
get { return _dbSnapInfoList; }
set { _dbSnapInfoList = value; }
}
}

通過(guò)這兩個(gè)配置文件,就可以實(shí)現(xiàn)對(duì)數(shù)據(jù)訪問(wèn)層負(fù)載均衡的靈活配置了,不過(guò)上面的DbSnapAppConfig還有一個(gè)非常重要的
屬性沒(méi)有介紹清楚,就是‘LoadBalanceScheduling',其接口聲明如下:
代碼
復(fù)制代碼 代碼如下:

/// <summary>
/// 負(fù)載均衡調(diào)度接口
/// </summary>
public interface ILoadBalanceScheduling
{
/// <summary>
/// 獲取應(yīng)用當(dāng)前負(fù)載均衡調(diào)度算法下的快照鏈接信息
/// </summary>
/// <returns></returns>
DbSnapInfo GetConnectDbSnap();
}

它就是負(fù)載均衡算法的實(shí)現(xiàn)接口,為了便于說(shuō)明在Discuz.EntLib中內(nèi)置的兩個(gè)負(fù)載均衡算法的實(shí)現(xiàn)情況,請(qǐng)先看下圖:

內(nèi)置的兩個(gè)負(fù)載均衡算法,一個(gè)是RoundRobinScheduling,即輪叫調(diào)度(Round Robin Scheduling)算法,它的實(shí)現(xiàn)比較簡(jiǎn)單,就是對(duì)從數(shù)據(jù)庫(kù)鏈接列表的依次遍歷,如下:
代碼
復(fù)制代碼 代碼如下:

/// <summary>
/// 輪叫調(diào)度(Round Robin Scheduling)算法
/// </summary>
public class RoundRobinScheduling : ILoadBalanceScheduling
{
private static object lockHelper = new object();
/// <summary>
/// 當(dāng)前的快照索引和權(quán)重信息
/// </summary>
static int curentSnapIndex = 0;
static RoundRobinScheduling()
{}
public DbSnapInfo GetConnectDbSnap()
{
lock (lockHelper)
{
if (curentSnapIndex >= DbSnapConfigs.GetEnableSnapList().Count)
curentSnapIndex = (curentSnapIndex) % DbSnapConfigs.GetEnableSnapList().Count;
return DbSnapConfigs.GetEnableSnapList()[curentSnapIndex++];
}
}
}

而另一種負(fù)載均衡算法就相對(duì)負(fù)載了,不過(guò)它也更符合實(shí)際的應(yīng)用場(chǎng)景,它使用了權(quán)重的方法來(lái)讓性能優(yōu)良的機(jī)器分到
更多的任務(wù)來(lái)均衡整個(gè)方案的性能,即權(quán)重輪詢(xún)調(diào)度算法,實(shí)現(xiàn)代碼如下:
代碼
復(fù)制代碼 代碼如下:

/// <summary>
/// 權(quán)重輪詢(xún)調(diào)度算法
/// http://www.pcjx.com/Cisco/zhong/209068.html
/// http://id-phatman.spaces.live.com/blog/cns!CA763CA8DB2378D1!627.entry
/// </summary>
public class WeightedRoundRobinScheduling : ILoadBalanceScheduling
{
private static object lockHelper = new object();
/// <summary>
/// 快照的權(quán)重列表
/// </summary>
static List<int> snapWeightList = new List<int>();
/// <summary>
/// 當(dāng)前的快照索引和權(quán)重信息
/// </summary>
static int curentSnapIndex, currentWeight;
/// <summary>
/// 快照權(quán)重列表中最大的權(quán)重值和最大公約數(shù)
/// </summary>
static int maxWeight, gcd;
static WeightedRoundRobinScheduling()
{
curentSnapIndex = -1;
currentWeight = 0;
snapWeightList = GetSnapWeightList();
maxWeight = GetMaxWeight(snapWeightList);
gcd = GCD(snapWeightList);
}
/// <summary>
/// 獲取應(yīng)用當(dāng)前負(fù)載均衡調(diào)度算法下的快照鏈接信息
/// </summary>
/// <returns></returns>
public DbSnapInfo GetConnectDbSnap()
{
lock (lockHelper)
{
DbSnapInfo current = RoundRobinScheduling();
if (current != null)
return current;
else
return DbSnapConfigs.GetEnableSnapList()[0];
}
}
/// <summary>
/// 獲取快照權(quán)重的列表
/// </summary>
/// <returns></returns>
static List<int> GetSnapWeightList()
{
List<int> snapWeightList = new List<int>();
foreach (DbSnapInfo dbSnapInfo in DbSnapConfigs.GetEnableSnapList())
{
snapWeightList.Add(dbSnapInfo.Weight);
}
return snapWeightList;
}
/// <summary>
/// 權(quán)重輪詢(xún)調(diào)度算法
/// </summary>
static DbSnapInfo RoundRobinScheduling()
{
while (true)
{
curentSnapIndex = (curentSnapIndex + 1) % DbSnapConfigs.GetEnableSnapList().Count;
if (curentSnapIndex == 0)
{
currentWeight = currentWeight - gcd;
if (currentWeight <= 0)
{
currentWeight = maxWeight;
if (currentWeight == 0)
return null;
}
}
if (DbSnapConfigs.GetEnableSnapList()[curentSnapIndex].Weight >= currentWeight)
return DbSnapConfigs.GetEnableSnapList()[curentSnapIndex];
}
}
/// <summary>
/// 獲取最大權(quán)重
/// </summary>
/// <param name="snapList"></param>
/// <returns></returns>
static int GetMaxWeight(List<int> snapWeightList)
{
int maxWeight = 0;
foreach (int snapWeight in snapWeightList)
{
if (maxWeight < snapWeight)
maxWeight = snapWeight;
}
return maxWeight;
}
/// <summary>
/// 獲取權(quán)重的最大公約數(shù)
/// </summary>
/// <returns></returns>
static int GCD(List<int> snapWeightList)
{
// 排序,得到數(shù)字中最小的一個(gè)
snapWeightList.Sort(new WeightCompare());
int minNum = snapWeightList[0];
// 最大公約數(shù)肯定大于等于1,且小于等于最小的那個(gè)數(shù)。
// 依次整除,如果余數(shù)全部為0說(shuō)明是一個(gè)約數(shù),直到打出最大的那個(gè)約數(shù)
int gcd = 1;
for (int i = 1; i <= minNum; i++)
{
bool isFound = true;
foreach (int snapWeight in snapWeightList)
{
if (snapWeight % i != 0)
{
isFound = false;
break;
}
}
if (isFound)
gcd = i;
}
return gcd;
}
/// <summary>
/// 實(shí)現(xiàn)IComparer接口,用于對(duì)數(shù)字列表進(jìn)行排序
/// </summary>
private class WeightCompare : System.Collections.Generic.IComparer<int>
{
public int Compare(int weightA, int weightB)
{
return weightA - weightB;
}
}
}

到這里,主要的功能代碼就介紹的差不多了,我們可以通過(guò)對(duì)dbsnap.config的相應(yīng)節(jié)點(diǎn)配置,來(lái)靈活定制我們的負(fù)載均衡方案。同時(shí),對(duì)一般開(kāi)發(fā)者而言,這種架構(gòu)是透明的,大家可以完全在不了解它的情況下開(kāi)發(fā)自己的數(shù)據(jù)訪問(wèn)功能,并通過(guò)相應(yīng)開(kāi)關(guān)來(lái)讓自己的代碼支持均衡負(fù)載。
當(dāng)然這個(gè)方案還有一些沒(méi)考慮到的問(wèn)題比如:
1.對(duì)‘主從數(shù)據(jù)庫(kù)的健康度檢查',即如果主或從數(shù)據(jù)庫(kù)出現(xiàn)故障的時(shí)候該如何處理,當(dāng)然在sqlserver中還提供了鏡像功能來(lái)解決類(lèi)似問(wèn)題,所以它也可做為一個(gè)備選方案。
2.當(dāng)主數(shù)據(jù)庫(kù)被發(fā)布出去后,主數(shù)據(jù)庫(kù)的表和存儲(chǔ)過(guò)程就會(huì)被‘鎖定',其不允許被再次修改了,所以還要繼續(xù)研究如何解決這一問(wèn)題。
原文鏈接:http://www.cnblogs.com/daizhj/archive/2010/06/21/dbsnap_master_slave_database.html  

作者: daizhj, 代震軍

相關(guān)文章

最新評(píng)論