简体   繁体   English

在数据库中保存非常繁忙的计数器的最佳实践

[英]Best practice to save very busy counter in db

I am developing a very busy web service which is supposed to get thousands of requests per second.我正在开发一个非常繁忙的网络服务,它应该每秒收到数千个请求。 I want that each request will update a counter field.我希望每个请求都会更新一个计数器字段。 How would i do that?我该怎么做? Saving the counter in db is very important so I will not lose the information in case the server dies.将计数器保存在 db 中非常重要,因此在服务器死机的情况下我不会丢失信息。 I have tried the following code, but this will be a huge bottle neck for thousands requests per second.我已经尝试了以下代码,但这将是每秒数千个请求的巨大瓶颈。 How would you do that?你会怎么做?

public void Upload(int organizationId)
{
  try
  {
    lock (UpadateLock)
    {
       using (var db = new DbContext())
       {
         Counter counter = db.Counters.Where(c => c.OrganizationId == organizationId).FirstOrDefault();
         counter.count++;
         db.SaveChanges();

       }
     }
   }
   catch (Exception ex)
   {

   }
}

If you absolutely cannot lose data when the server dies then you must write to a persistent store for each increment.如果服务器死机时您绝对不会丢失数据,那么您必须为每个增量写入持久存储。

The question is just what store to use.问题只是使用什么商店。

You can certainly do it with SQL.你当然可以用 SQL 做到这一点。 A simple query like this is not too expensive.像这样的简单查询并不太昂贵。 You can benchmark this to see if the overhead is acceptable.您可以对此进行基准测试,以查看开销是否可以接受。 Measure CPU usage on web server and SQL server.测量 Web 服务器和 SQL 服务器上的 CPU 使用率。 Also measure disk usage and transaction log size.还要测量磁盘使用情况和事务日志大小。

Redis might turn out to be a really good database for this. Redis 可能会成为一个非常好的数据库。 It is known to be fast and it supports server-side increments.众所周知,它速度很快,并且支持服务器端增量。

You can also scale out this workload by writing increments to multiple servers (randomly picking one).您还可以通过将增量写入多个服务器(随机选择一个)来扩展此工作负载。

You can use any other data store as well.您也可以使用任何其他数据存储。 If it does not support incrementing natively you can instead insert new rows.如果它本身不支持递增,您可以插入新行。 Then, have a background process that periodically aggregates those rows so that they don't keep accumulating.然后,有一个后台进程定期聚合这些行,以便它们不会不断累积。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM