2010-02-03 69 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; 
    } 
}