C#中对于缓存Cache的使用
1、引入:using System.Web.Caching;命名空间
2、增加缓存添加方法:
/// <summary>
///
/// </summary>
/// <param name="key">缓存key,全局唯一</param>
/// <param name="value">缓存值</param>
/// <param name="minutes">缓存时间(分钟)</param>
/// <param name="useAbsoluteExpiration">是否绝对过期</param>
public static void Add(string key, object value, int minutes, bool useAbsoluteExpiration)
{
if (key != null && value != null)
{
if (useAbsoluteExpiration)
{
HttpContext.Current.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(minutes), Cache.NoSlidingExpiration);
}
else
{
HttpContext.Current.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, minutes, 0));
}
}
}
3、增加移除缓存的方法:
public static object Remove(string key)
{
return HttpContext.Current.Cache.Remove(key);
}
4、增加移除全部缓存的方法:
public static void RemoveAll()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
System.Collections.IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
if (CacheEnum == null) return;
while (CacheEnum.MoveNext())
{
Remove(CacheEnum.Key.ToString());
}
}
5、在使用缓存的地方,直接调用以上方法即可。