c#编写的高并发数据库控制访问代码

代码的作用在于保证在上端缓存服务失效(一般来说概率比较低)时,形成倒瓶颈,从而能够保护数据库,数据库宕了,才是大问题(比如影响其他应用)。

假设(非完全正确数据,仅做示例):
每秒支持10,000,000次查询(千万);
一次读库需要耗时:1ms;
修改内存变量需要耗时:0.001ms;
那么:
每秒最终访问的数据库的请求数量 < 1000
其他的9,900,000个请求会返回到其他页面。这就是为啥很多抢单网站有人可以访问,而有人得到繁忙中页面的原因。

微观到1ms来看,在currentValidSessionID == -1的时间是 1ms,从而平均会有10000条记录涌入。
currentValidSessionID从-1变为其他值的时间为0.001ms,这个时间内,


  lock (databaseDoor)

  {

    // now there is only one request can reach below codes.

    if (currentValidSessionID == -1)

    {

      currentValidSessionID = currentRequest.SessionID;

    }

  }

平均会有 10000×0.001=10条记录会执行到上述这段代码,操作系统会为锁形成等待序列。
那么我们的目标是,每毫秒只允许一次读库(因为其他应用也会使用),所以我们只希望这进入的10条,最终只有一条能够继续前进。
那么这就是


if (currentValidSessionID == -1)

{

}

的作用了。再次进行一次判断,进入原子保护队列的请求,也只有一个能够继续。

一点思考:
其实对于一个主频能上N GHz的服务器来说,一个内存数赋值给另一个内存数据就是1~4条指令(平均2条,两次MOV操作),也就是2/N ns时间,而不是我们上述假设的 1000ns(0.001ms)。其实不用原子,我们已经可以把千亿级请求的访问数控制在个位数。
不过一个架构师,如果可以用一个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

        }

    }

}

以上就是本文所述的全部内容了,希望对大家学习C#的高并发编程能够有所帮助。