加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

是否有任何asp.net数据缓存支持缓存条目的背景填充?

发布时间:2020-12-16 04:34:09 所属栏目:asp.Net 来源:网络整理
导读:我们有一个数据驱动的ASP.NET网站,该网站使用标准模式进行数据缓存(从MSDN改编): public DataTable GetData(){ string key = "DataTable"; object item = Cache[key] as DataTable; if((item == null) { item = GetDataFromSQL(); Cache.Insert(key,item,nu
我们有一个数据驱动的ASP.NET网站,该网站使用标准模式进行数据缓存(从MSDN改编):
public DataTable GetData()
{
   string key = "DataTable";
   object item = Cache[key] as DataTable;
   if((item == null)
   {
      item = GetDataFromSQL();
      Cache.Insert(key,item,null,DateTime.Now.AddSeconds(300),TimeSpan.Zero;
   }
   return (DataTable)item;
}

这样做的问题是对GetDataFromSQL()的调用是昂贵的,并且该站点的使用相当高.因此,每隔五分钟,当缓存丢失时,该站点变得非常“粘滞”,而许多请求正在等待检索新数据.

我们真正想要的是旧数据保持最新,同时在后台定期重新加载新数据. (因此有人可能会看到六分钟的数据并不是一个大问题 – 数据不是时间敏感的).这是我自己可以编写的内容,但知道是否有任何替代缓存引擎(我知道Velocity,memcache等名称)支持这种情况会很有用.或者我错过了标准ASP.NET数据缓存的一些明显技巧?

解决方法

您应该能够使用CacheItemUpdateCallback委托,它是第6个参数,它是使用ASP.NET Cache进行插入的第4个重载:
Cache.Insert(key,value,dependancy,absoluteExpiration,slidingExpiration,onUpdateCallback);

以下应该有效:

Cache.Insert(key,Cache.NoSlidingExpiration,itemUpdateCallback);

private void itemUpdateCallback(string key,CacheItemUpdateReason reason,out object value,out CacheDependency dependency,out DateTime expiriation,out TimeSpan slidingExpiration)
{
    // do your SQL call here and store it in 'value'
    expiriation = DateTime.Now.AddSeconds(300);
    value = FunctionToGetYourData();
}

从MSDN开始:

When an object expires in the cache,
ASP.NET calls the
CacheItemUpdateCallback method with
the key for the cache item and the
reason you might want to update the
item. The remaining parameters of this
method are out parameters. You supply
the new cached item and optional
expiration and dependency values to
use when refreshing the cached item.

The update callback is not called if
the cached item is explicitly removed
by using a call to Remove().

If you want the cached item to be
removed from the cache,you must
return null in the expensiveObject
parameter. Otherwise,you return a
reference to the new cached data by
using the expensiveObject parameter.
If you do not specify expiration or
dependency values,the item will be
removed from the cache only when
memory is needed.

If the callback method throws an
exception,ASP.NET suppresses the
exception and removes the cached
value.

我没有对此进行过测试,因此您可能需要对其进行一些修补,但它应该为您提供您想要完成的基本想法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读