更新:我放弃了缓存系统,转而使用数据库解决方案 - 坑洼。
我有一个后端MVC控制器,我需要数据缓存。我使用 MemoryCache.Default 来存储键/值对,没什么大不了的。没关系政策和到期时间,我得到了。令我神秘的是为什么我的缓存在我第一次访问密钥(重新获取值)后被清理掉了。如果我不访问缓存的项目,最终该项目将过期,我的删除处理程序被调用 - 这一切都很好。但是当我第一次检索项目时,我的删除处理程序会在一段时间后被调用。 ChacheEntryRemovedReason 设置为:
CacheSpecificEviction // A cache entry was evicted for as reason that is defined by a particular cache implementation.
我找不到任何解释这意味着什么。 这里令人费解的是,当我在处理程序中调试时(以及在后续的控制器调用中)检查缓存对象时,缓存枚举为空。如果我“设置”(添加)一个新的CacheItem到缓存,我可以再次访问该密钥一次,并重复历史记录。 这种行为就像一个一次性的缓存机制,我完全不需要。 任何帮助或评论将不胜感激!
一些简化的代码只是为了它的乐趣:
private static ObjectCache cache = MemoryCache.Default;
internal void insertInCache(string key, int value) {
CacheItemPolicy policy= new CacheItemPolicy() {
AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration,
Priority = CacheItemPriority.NotRemovable,
SlidingExpiration = TimeSpan.FromMinutes(ITEM_EXPIRE_TIME),
RemovedCallback = new CacheEntryRemovedCallback(RemovedHandler)
};
cache.Set(key, value, policy);
}
static void RemovedHandler(CacheEntryRemovedArguments args) {
if(args.RemovedReason == CacheEntryRemovedReason.Expired) {
//do something - or i actually want it to disappear when expired
} else {
cache.Set(args.CacheItem, somepolicy);//reinsert to keep in cache
}
}
//Apparently this triggers some cache mong mode
internal void getSome(string key){
int thisIsWhatIWanted = (int)cache.GetCacheItem(key).Value;
}
这只是示例代码,所以请不要唠叨我的技巧。 我自己最好的猜测是它可能与缓存没有正确设置,MVC巫术或我在调试IIS上运行我的应用程序(视觉研究)