如何在缓存中存储数据表以重用它?

在我的应用程序中,我使用了通用处理程序处理请求。

我想要机制,如果第一次请求来到处理程序,它向服务器发出请求然后缓存整个数据表,所以对于即将到来的请求,如果下一个请求的产品代码存在于缓存的数据表中,它不应该去服务器获取数据再次..应该只检查数据表的数据。

所以你能解释一下我如何在缓存中设置数据表。

沿着这些方向的东西?

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