2011-07-26 44 views
7

在我的應用程序中,我使用通用處理程序來處理請求。如何將數據表存儲在緩存中以重用它?

我想要的機制,如果第一次請求來到處理程序,它向服務器發出請求,然後緩存整個數據表,所以對於即將到來的請求,如果下一個請求的產品代碼存在於緩存的數據表中,它不應該去到服務器再次獲取數據。它應該只檢查數據表的數據。

那麼你能解釋我如何設置緩存中的數據表。

回答

21

東西沿着這些路線?

public DataTable GetDataTableFromCacheOrDatabase() 
{ 
    DataTable dataTable = HttpContext.Current.Cache["secret key"] as DataTable; 
    if(dataTable == null) 
    { 
     dataTable = GetDataTableFromDatabase(); 
     HttpContext.Current.Cache["secret key"] = dataTable; 
    } 
    return dataTable; 
} 

如果數據表發生變化,您將需要某種機制將數據表從緩存中清除。例如,您可以使用SqlCacheDependency

按照要求,清除緩存小時表添加後,你會怎麼做:

HttpContext.Current.Cache.Insert("secret key", dataTable, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); 
+2

非線程安全......如果在「if」和「return」之間刪除緩存條目會怎麼樣? –

+0

@Thomas Levesque - 這是不太可能的。 – JonH

+2

@JonH,不可能發生的事情總是發生......如果可能發生,它可能遲早會出現(這大致就是墨菲定律背後的想法) –

1

你可以使用:

HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance; 
4

試試這個

DataTable mytable; 
String key = "key" 
if(HttpContext.Current.Cache[Key] ==null) 
{ 
     mytable = GetDTFromDB(); 
     if(mytable.Rows.Count > 0) 
      HttpContext.Current.Cache.Insert(strKey, mytable, Nothing, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); 
    else 
     mytable = HttpContext.Current.Cache[strKey]; 
    } 
0

,你可以寫你的表中的屬性像

public DataTable CachedTable { get{ 
     if(Cache["CachedTable"] == null) 
    { 
     Cache["CachedTable"]= //get from databse 
     } 
     return Cache["CachedTable"]; 
    } } 
相關問題