[英]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.