简体   繁体   English

ASP.net缓存-正确使用

[英]ASP.net Cacheing - Proper Usage

I am creating a web application and am having an issue with my cacheing. 我正在创建一个Web应用程序,并且缓存出现问题。

My application has a large amount of data that I want to try and not call from the sql database everytime i need the info. 我的应用程序有大量的数据,我想尝试而不每次需要信息时都不从sql数据库中调用。

I have tried to use caching in the following way: 我尝试通过以下方式使用缓存:

        public static List<DAL.EntityClasses.AccountsEntity> Accounts
    {
        get
        {
            if (HttpContext.Current.Cache["Account"] == null)
            {
                HttpContext.Current.Cache.Insert("Account", LoadAccounts(), null, DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return (List<DAL.EntityClasses.AccountsEntity>)HttpContext.Current.Cache["Account"];
        }
    }

The problem is that it appears that as I am adding items to the Cache, the items that I have already cached get removed. 问题是,当我向缓存添加项目时,已经缓存的项目似乎被删除了。

So most calls are calling the DB to get the data for the cache. 因此,大多数调用都在调用数据库以获取高速缓存的数据。

Where have I gone wrong? 我哪里出问题了?

Thanks 谢谢

This is normal for a LRU cache - least used items get pushed out as the cache fills up capacity. 对于LRU缓存,这是正常现象-最少使用的项目会在缓存填满后被推出。

Configure your cache to larger amounts of data. 将缓存配置为包含更多数据。

Just FYI: Theres a problem with your implementation of the Accounts property, that is not releated to your original question, but may cause problems in the future: 仅供参考:您实施Accounts属性时出现问题,该问题与您最初的问题无关,但将来可能会引起问题:

What could happen is that between this line 可能发生的是这条线之间

if (HttpContext.Current.Cache["Account"] == null)

and this line: 这行:

 return (List<DAL.EntityClasses.AccountsEntity>)HttpContext.Current.Cache["Account"]; 

your cache could be cleared / the Account entry could be deleted from the cache. 您的缓存可以清除/帐户条目可以从缓存中删除。

a better implementation would be: 更好的实现是:

public static List<DAL.EntityClasses.AccountsEntity> Accounts             
{             
    get             
    {  
      List<DAL.EntityClasses.AccountsEntity> accounts = 
       HttpContext.Current.Cache["Account"] as List<DAL.EntityClasses.AccountsEntity> 

      if(accounts == null)
      {
        accounts = LoadAccounts();
        HttpContext.Current.Cache.Insert("Account", accounts, null, DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration);          
      }  
      return accounts;
   }
}

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

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