队列访问数据库,以避免多个缓存项 [英] Queue access to the database to avoid multiple cache items

查看:253
本文介绍了队列访问数据库,以避免多个缓存项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个音乐相关的ASP.NET网站,从第一个请求数据库缓存大量的静态信息。

I have a music related ASP.NET web site which caches a lot of static information from the database on the first request.

有时,应用程序复位,而应用程序在重负载,那么所有的http请求去数据库检索静态数据,并将它缓存为其他请求清除缓存。

Sometimes, the application is reset and cache is cleared while the application is on heavy load and then all http requests go to the database to retrieve that static data and cache it for other requests.

如何才能确保只有一个请求到数据库和缓存结果,让其他的请求只是读取缓存信息,并一遍又一遍不会不必要获得相同的信息。

How can I ensure that only one request go to the database and cache the results, so that other request simply read that info from cache and not needlessly retrieve the same info over and over again.

我可以使用螺纹锁固?例如,我可以这样做锁(这个){DB访问这里}

Can I use thread locking? For example, can I do something like lock(this) { db access here }?

推荐答案

是的,在你的缓存code,你会希望把你的数据库访问code一内锁块。但是,不要锁定这个。通常情况下你会做这样的事情。

Yes, in your caching code, you'll want to put your database-accessing code inside a lock block. However, don't lock on this. Typically you'd do something like

private static readonly object staticObjectToLockOn = new object();

...

if (cache[cacheKey] == null)
{
   lock(staticObjectToLockOn)
   {
      // double-check the cache is still null inside the lock
      if (cache[cacheKey] == null)
      {
         // get data from the database, add to cache
      }
   }
}

这篇关于队列访问数据库,以避免多个缓存项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆