在我的 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 或代码“index”访问缓存。如果未找到,则如上所示检索事件并编制索引。
这种方法会导致什么问题吗?
ASP 可以决定只删除其中一个索引。如果我通过该索引访问缓存,它将获取该项目并再次重新编制索引,这没问题。
更新:
我的主要问题是我是否必须为存储对象两次付费,或者它是否只是对存储在缓存中的同一对象的引用?
最佳答案
您可以使用 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 }));
}
关于c# - 具有多个索引的 ASP.NET 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7387367/