代碼的作用在于保證在上端緩存服務(wù)失效(一般來(lái)說(shuō)概率比較低)時(shí),形成倒瓶頸,從而能夠保護(hù)數(shù)據(jù)庫(kù),數(shù)據(jù)庫(kù)宕了,才是大問(wèn)題(比如影響其他應(yīng)用)。
假設(shè)(非完全正確數(shù)據(jù),僅做示例):
每秒支持10,000,000次查詢(xún)(千萬(wàn));
一次讀庫(kù)需要耗時(shí):1ms;
修改內(nèi)存變量需要耗時(shí):0.001ms;
那么:
每秒最終訪問(wèn)的數(shù)據(jù)庫(kù)的請(qǐng)求數(shù)量 < 1000
其他的9,900,000個(gè)請(qǐng)求會(huì)返回到其他頁(yè)面。這就是為啥很多搶單網(wǎng)站有人可以訪問(wèn),而有人得到繁忙中頁(yè)面的原因。
微觀到1ms來(lái)看,在currentValidSessionID == -1的時(shí)間是 1ms,從而平均會(huì)有10000條記錄涌入。
currentValidSessionID從-1變?yōu)槠渌档臅r(shí)間為0.001ms,這個(gè)時(shí)間內(nèi),
代碼如下:
lock (databaseDoor)
{
// now there is only one request can reach below codes.
if (currentValidSessionID == -1)
{
currentValidSessionID = currentRequest.SessionID;
}
}
平均會(huì)有 10000×0.001=10條記錄會(huì)執(zhí)行到上述這段代碼,操作系統(tǒng)會(huì)為鎖形成等待序列。
那么我們的目標(biāo)是,每毫秒只允許一次讀庫(kù)(因?yàn)槠渌麘?yīng)用也會(huì)使用),所以我們只希望這進(jìn)入的10條,最終只有一條能夠繼續(xù)前進(jìn)。
那么這就是
代碼如下:
if (currentValidSessionID == -1)
{
}
的作用了。再次進(jìn)行一次判斷,進(jìn)入原子保護(hù)隊(duì)列的請(qǐng)求,也只有一個(gè)能夠繼續(xù)。
一點(diǎn)思考:
其實(shí)對(duì)于一個(gè)主頻能上N GHz的服務(wù)器來(lái)說(shuō),一個(gè)內(nèi)存數(shù)賦值給另一個(gè)內(nèi)存數(shù)據(jù)就是1~4條指令(平均2條,兩次MOV操作),也就是2/N ns時(shí)間,而不是我們上述假設(shè)的 1000ns(0.001ms)。其實(shí)不用原子,我們已經(jīng)可以把千億級(jí)請(qǐng)求的訪問(wèn)數(shù)控制在個(gè)位數(shù)。
不過(guò)一個(gè)架構(gòu)師,如果可以用一個(gè)99.99%安全的方案,就絕對(duì)不用99.9%。 SO。
代碼如下:
public static long currentValidSessionID = -1;
public static object databaseDoor = new object();
void readDatabase(Request currentRequest)
{
// use currentValidSessionID to filter out other requests came in during the execute time gap
if (currentValidSessionID == -1)
{
// use object-lock to filter out other requests came in during the variable change time gap.
lock (databaseDoor)
{
// now there is only very little number of requests can reach below codes.
if (currentValidSessionID == -1)
{ // now there will be only one request can access the database
currentValidSessionID = currentRequest.SessionID;
}
}
}
if (currentValidSessionID == currentRequest.SessionID)
{ // here is the one !
try
{
// use transaction to guarantee the execute time to void block
// access database codes go here
}
catch()
{
// exception codes go here
}
finally
{
currentValidSessionID = -1; // recover to original state
}
}
}
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄