国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2020-01-24 02:07:37
字體:
供稿:網(wǎng)友

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

假設(shè)(非完全正確數(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),

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

  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)會為鎖形成等待序列。
那么我們的目標(biāo)是,每毫秒只允許一次讀庫(因為其他應(yīng)用也會使用),所以我們只希望這進(jìn)入的10條,最終只有一條能夠繼續(xù)前進(jìn)。
那么這就是

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

if (currentValidSessionID == -1)
{
}

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

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

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 同心县| 芒康县| 五河县| 舟山市| 封丘县| 关岭| 宁安市| 修文县| 睢宁县| 县级市| 嘉祥县| 土默特左旗| 京山县| 云南省| 台中市| 库车县| 海原县| 田东县| 肥东县| 梓潼县| 泗阳县| 米脂县| 开化县| 蓬溪县| 台江县| 澜沧| 吴忠市| 射阳县| 东至县| 融水| 台中市| 广宁县| 安图县| 金平| 海原县| 黄浦区| 洱源县| 浪卡子县| 扎赉特旗| 崇礼县| 外汇|