2010-02-03 72 views
0

我正在创建一个Web应用程序,并且遇到缓存问题。ASP.net缓存 - 正确使用

我的应用程序有大量的数据,我想尝试,而不是每次我需要信息时从sql数据库调用。

我曾尝试以下列方式使用缓存:

 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"]; 
     } 
    } 

的问题是,它似乎是为我添加项目到缓存中,我已经在项目缓存移除。

因此大多数调用都在调用数据库来获取缓存数据。

我哪里出错了?

感谢

回答

3

这是正常的LRU缓存 - 最少使用项目将被推出来的缓存满容量。

Configure your cache更大的数据量。

+0

谢谢。如果我在缓存中加载一些演出,假设服务器完成任务,这是否是一个问题?我想所有的账户,用户,客户等itmes像我不想添加更改的订单。 – SetiSeeker 2010-02-03 09:32:02

+0

不是一个问题,如果你有它的记忆。不要缓存整个数据库,缓存不变的内容,并确保在缓存项目上设置适当的到期时间。 – Oded 2010-02-03 09:36:04

1

仅供参考: 即使世界与你的执行账户性质的问题,那就是不相关型号到你原来的问题,但可能会导致在未来的问题:

可能发生的是,这条路线之间

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

这行:

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

缓存ç应该被清除/账户条目可以从缓存中删除。

一个更好的实现是:

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; 
    } 
}