我最终使用的解决方案在System.Runtime.Caching
命名空间中涉及MemoryCache
。这里是结束了对缓存我收集工作代码:
//If the data exists in cache, pull it from there, otherwise make a call to database to get the data
ObjectCache cache = MemoryCache.Default;
var peopleData = cache.Get("PeopleData") as List<People>;
if (peopleData != null)
return peopleData ;
peopleData = GetAllPeople();
CacheItemPolicy policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30)};
cache.Add("PeopleData", peopleData, policy);
return peopleData;
这里是另一种方式,我发现使用Lazy<T>
考虑到锁定和并发性。总归功于这个帖子:How to deal with costly building operations using MemoryCache?
private IEnumerable<TEntity> GetFromCache<TEntity>(string key, Func<IEnumerable<TEntity>> valueFactory) where TEntity : class
{
ObjectCache cache = MemoryCache.Default;
var newValue = new Lazy<IEnumerable<TEntity>>(valueFactory);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) };
//The line below returns existing item or adds the new value if it doesn't exist
var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<IEnumerable<TEntity>>;
return (value ?? newValue).Value; // Lazy<T> handles the locking itself
}
是写这之后,我发现'MemoryCache'在'System.Runtime.Caching'命名空间看起来很完美。如果AppPool回收的话,我可以放弃数据的警告是可以的,因为我只是试图阻止在每次API调用时重新调用数据库。使用'MemoryCache.Get()'和'MemoryCache.Add()'似乎对我来说效果不错。 'AddOrGetExisting()'看起来很酷,但不适合我的情况;它在调用之前仍然需要先从数据库获取数据。我设定了30分钟的“绝对时间”。 – atconway 2013-05-08 17:35:23
作为帮助人们的标记,Azure推荐的缓存技术现在是Redis。如果您的API有一个以上的实例,则需要Redis或其他分布式缓存。 Azure托管缓存现在非常隐蔽,只能从Powershell访问。他们只是在那里帮助那些以前使用过它的人。 – 2015-05-28 10:07:41
如果您所做的只是缓存一些WebApi数据调用,则Redis过于昂贵。 – 2017-02-02 21:47:28