最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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

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

復制代碼 代碼如下:

  lock (databaseDoor)
  {
    // now there is only one request can reach below codes.
    if (currentValidSessionID == -1)
    {
      currentValidSessionID = currentRequest.SessionID;
    }
  }

平均會有 10000×0.001=10條記錄會執(zhí)行到上述這段代碼,操作系統(tǒng)會為鎖形成等待序列。
那么我們的目標是,每毫秒只允許一次讀庫(因為其他應用也會使用),所以我們只希望這進入的10條,最終只有一條能夠繼續(xù)前進。
那么這就是

復制代碼 代碼如下:

if (currentValidSessionID == -1)
{
}

的作用了。再次進行一次判斷,進入原子保護隊列的請求,也只有一個能夠繼續(xù)。

一點思考:
其實對于一個主頻能上N GHz的服務器來說,一個內(nèi)存數(shù)賦值給另一個內(nèi)存數(shù)據(jù)就是1~4條指令(平均2條,兩次MOV操作),也就是2/N ns時間,而不是我們上述假設的 1000ns(0.001ms)。其實不用原子,我們已經(jīng)可以把千億級請求的訪問數(shù)控制在個位數(shù)。
不過一個架構(gòu)師,如果可以用一個99.99%安全的方案,就絕對不用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
        }
    }
}

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

相關文章

最新評論

汉川市| 武陟县| 乃东县| 兴化市| 汝阳县| 山西省| 怀柔区| 长汀县| 东乡| 霞浦县| 犍为县| 四会市| 聂拉木县| 太仓市| 河西区| 波密县| 霞浦县| 阿鲁科尔沁旗| 贵港市| 亚东县| 石泉县| 青海省| 司法| 潮州市| 石渠县| 桐乡市| 永登县| 赣榆县| 蓬安县| 江阴市| 永胜县| 湘阴县| 泽普县| 昂仁县| 定襄县| 中方县| 丹阳市| 洪湖市| 桐庐县| 广宁县| 铜川市|