专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

C#编写高并发数据库控制

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 0:47:09       共计:3631 浏览

往往大数据量,高并发时, 瓶颈都在数据库上, 好多人都说用数据库的复制,发布, 读写分离等技术, 但主从数据库之间同步时间有延迟.代码的作用在于保证在上端缓存服务失效(一般来说概率比较低)时,形成倒瓶颈,从而能够保护数据库,数据库宕了,才是大问题(比如影响其他应用)。

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

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

1 2 3 4 5 6 7 8 9 lock (databaseDoor) {   // now there is only one request can reach below codes.   if (currentValidSessionID == -1)   {     currentValidSessionID = currentRequest.SessionID;   } }


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

1 2 3 if (currentValidSessionID == -1) { }


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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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# Task 多任务 限制Task并发数量 | ·下一条:C# 高并发、抢单解决思路

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有