使用多个索引进行ASP.NET缓存

时间:2011-09-12 11:50:46

标签: c# linq-to-sql

在我的DataCache中,我需要使用两个索引来缓存对象。

说我像这样缓存:

Campaign campaign = //get campaign from db

HttpContext.Current.Cache.Add(
"Campaigns.Id."+campaign.Id.ToString(), 
campaign,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);

HttpContext.Current.Cache.Insert("Campaigns.Code."+campaign.Code,
campaign,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);

我尝试使用Id或Code“index”访问缓存。如果未找到,则会检索广告系列并将其编入索引,如上所示。

这种方法可以导致任何问题吗?

ASP可以决定只删除其中一个索引。如果我通过该索引访问缓存,它将获取该项并再次重新索引,这没关系。

更新:

我的主要问题是我是否需要支付两次存储对象的费用,或者它是否只是对存储在缓存中的同一对象的引用?

1 个答案:

答案 0 :(得分:4)

您可以确保使用CacheDependency对象一起删除这两个条目。这是更新的插入语句。这使得到期时间不再需要。

HttpContext.Current.Cache.Insert(
  "Campaigns.Code." + campaign.Code, 
  campaign, 
  new CacheDependency(null, new [] {"Campaigns.Id."+campaign.Id.ToString()}));

但实际上两种变体都很好。

编辑:您应该插入第二个条目取决于添加第一个条目的成功与否。考虑多个请求要求不在缓存中的对象的情况。一场典型的比赛。所有这些都创建了数据(很好),其中一个可以成功调用Add(...)(罚款),但所有这些都可以成功调用Insert(...)(可能很糟糕)。最终可能会为两个索引返回不同的对象。

我建议您对代码进行以下更改:

Campaign campaign = //get campaign from db
string id = "Campaigns.Id." + campaign.Id.ToString();
object old = HttpContext.Current.Cache.Add(
    id, campaign, null,
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.Normal,
    null);
if (old == null) {
    // the object was successfully added
    HttpContext.Current.Cache.Insert(
        "Campaigns.Code." + campaign.Code, 
        campaign, 
        new CacheDependency(null, new [] { id }));
}