System.Runtime.Cache立即过期
问题描述:
我有一个网页缓存一些查询字符串值为30秒,以便它不会收到重复的值。我正在使用以下类:System.Runtime.Cache立即过期
public class MyCache {
private static ObjectCache cache = MemoryCache.Default;
public MyCache() { }
public void Insert(string key, string value)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.Priority = CacheItemPriority.Default;
policy.SlidingExpiration = new TimeSpan(0, 0, 30);
policy.RemovedCallback = new CacheEntryRemovedCallback(this.Cacheremovedcallback);
cache.Set(key, value, policy);
}
public bool Exists(string key)
{
return cache.Contains(key);
}
public void Remove(string key)
{
cache.Remove(key);
}
private void Cacheremovedcallback(CacheEntryRemovedArguments arguments)
{
FileLog.LogToFile("Cache item removed. Reason: " + arguments.RemovedReason.ToString() + "; Item: [" + arguments.CacheItem.Key + ", " + arguments.CacheItem.Value.ToString() + "]");
}
}
这工作得很好,几个星期后突然缓存不再保留值。 CacheRemoved回调在将项目插入缓存后立即触发,并且我找到了删除的原因:CacheSpecificEviction 这是在Windows Server 2008 SP1,IIS7.5与.NET 4.0上运行。在此期间没有更改应用于操作系统或IIS。
有没有办法解决这个问题,如果没有,是否有更好的缓存解决方案在网页中使用?
预先感谢您。
答
试试这个:
policy.AbsoluteExpiration = DateTime.Now.AddSeconds(30);
这就是我如何使用缓存:
public static class CacheHelper
{
private static ObjectCache _cache;
private const Double ChacheExpirationInMinutes = 10;
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="entity">item cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T entity, string key) where T : class
{
if (_cache == null)
{
_cache = MemoryCache.Default;
}
if (_cache.Contains(key))
_cache.Remove(key);
CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddMinutes(ChacheExpirationInMinutes);
_cache.Set(key, entity, cacheItemPolicy);
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
if (_cache == null)
{
_cache = MemoryCache.Default;
return;
}
_cache.Remove(key);
}
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <returns>Cached item as type</returns>
public static T Get<T>(string key) where T : class
{
if (_cache == null)
{
_cache = MemoryCache.Default;
}
try
{
return (T)_cache.Get(key);
}
catch
{
return null;
}
}
}
是否可以缓存已经达到了它的极限尺寸是多少?是否由于空间限制而删除旧的项目? – 2013-02-15 10:27:10
看到这个帖子的解释。 http://stackoverflow.com/questions/5380875/caching-data-net-4-0-asp-net – 2013-02-15 10:42:42