[英]How to store datatable in cache to reuse it?
在我的應用程序中,我使用了通用處理程序來處理請求。
我想要一種機制,例如第一次請求到達處理程序時,它先向服務器發出請求,然后將整個數據表緩存起來,因此對於即將到來的請求,如果下一個請求的產品代碼存在於緩存的數據表中,則不應將其轉到服務器進行提取數據再次..它應該只檢查數據表的數據。
所以你能解釋一下如何在緩存中設置數據表嗎?
遵循這些原則?
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);
嘗試這個
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];
}
您可以使用:
HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance;
您可以為表格編寫屬性,例如
public DataTable CachedTable { get{
if(Cache["CachedTable"] == null)
{
Cache["CachedTable"]= //get from databse
}
return Cache["CachedTable"];
} }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.