如何将数据表存储在缓存中以重用它? [英] How to store datatable in cache to reuse it?

查看:27
本文介绍了如何将数据表存储在缓存中以重用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application i have used Generic handler to serve requests.

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

I want mechanism like if the first time request comes to handler ,it makes a request to server and then Cache whole datatable, so for upcoming request if the next requested productcode is exist in the datatable of cache, it should not go to server for fetching data again..it should check data of datatable only.

那么你能解释一下我如何在缓存中设置数据表吗??

推荐答案

有什么类似的吗?

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.

You're going to need some mechanism to flush the data table from the cache if it changes. For example you could use an SqlCacheDependency.

根据要求,要在添加表一小时后清除缓存,您可以执行以下操作:

As requested, to clear the cache an hour after the table is added you would do:

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

这篇关于如何将数据表存储在缓存中以重用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆