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

c#編寫的高并發(fā)數(shù)據(jù)庫控制訪問代碼

 更新時(shí)間:2015年03月17日 15:04:39   投稿:hebedich  
往往大數(shù)據(jù)量,高并發(fā)時(shí), 瓶頸都在數(shù)據(jù)庫上, 好多人都說用數(shù)據(jù)庫的復(fù)制,發(fā)布, 讀寫分離等技術(shù), 但主從數(shù)據(jù)庫之間同步時(shí)間有延遲.

代碼的作用在于保證在上端緩存服務(wù)失效(一般來說概率比較低)時(shí),形成倒瓶頸,從而能夠保護(hù)數(shù)據(jù)庫,數(shù)據(jù)庫宕了,才是大問題(比如影響其他應(yīng)用)。

假設(shè)(非完全正確數(shù)據(jù),僅做示例):
每秒支持10,000,000次查詢(千萬);
一次讀庫需要耗時(shí):1ms;
修改內(nèi)存變量需要耗時(shí):0.001ms;
那么:
每秒最終訪問的數(shù)據(jù)庫的請(qǐng)求數(shù)量 < 1000
其他的9,900,000個(gè)請(qǐng)求會(huì)返回到其他頁面。這就是為啥很多搶單網(wǎng)站有人可以訪問,而有人得到繁忙中頁面的原因。

微觀到1ms來看,在currentValidSessionID == -1的時(shí)間是 1ms,從而平均會(huì)有10000條記錄涌入。
currentValidSessionID從-1變?yōu)槠渌档臅r(shí)間為0.001ms,這個(gè)時(shí)間內(nèi),

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

  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)是,每毫秒只允許一次讀庫(因?yàn)槠渌麘?yīng)用也會(huì)使用),所以我們只希望這進(jìn)入的10條,最終只有一條能夠繼續(xù)前進(jìn)。
那么這就是

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

if (currentValidSessionID == -1)
{
}

的作用了。再次進(jìn)行一次判斷,進(jìn)入原子保護(hù)隊(duì)列的請(qǐng)求,也只有一個(gè)能夠繼續(xù)。

一點(diǎn)思考:
其實(shí)對(duì)于一個(gè)主頻能上N GHz的服務(wù)器來說,一個(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)求的訪問數(shù)控制在個(gè)位數(shù)。
不過一個(gè)架構(gòu)師,如果可以用一個(gè)99.99%安全的方案,就絕對(duì)不用99.9%。 SO。

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

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
        }
    }
}

以上就是本文所述的全部?jī)?nèi)容了,希望對(duì)大家學(xué)習(xí)C#的高并發(fā)編程能夠有所幫助。

相關(guān)文章

最新評(píng)論