using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
namespace CP.Cache
{
public class BaseCache
{
protected static volatile System.Web.Caching.Cache cache = HttpRuntime.Cache;
///
/// cache是否存在
///
///
///
public static bool IsExist(string k)
{
if (string.IsNullOrEmpty(k))
return false;
return cache[k] != null;
}
///
/// 获取cache
///
///
///
///
public static T Get(string k)
{
if (!string.IsNullOrEmpty(k) && cache[k] != null)
{
return (T)cache.Get(k);
}
return default(T);
}
///
/// 添加cache
///
///
/// key
/// value
/// 绝对过期时间
public static void Add(string k,T v,int m = 0)
{
if(!string.IsNullOrEmpty(k) && v != null)
{
if (m > 0)
{
cache.Insert(k, v, null, DateTime.Now.AddMinutes(m), System.Web.Caching.Cache.NoSlidingExpiration);
}
else
{
cache.Insert(k, v);
}
}
}
///
/// 移出Cache
///
///
public static void Remove(string k)
{
if(IsExist(k))
{
cache.Remove(k);
}
}
///
/// 批量移出cache
///
///
public static void RemoveList(string k)
{
if (!string.IsNullOrEmpty(k))
{
var e = cache.GetEnumerator();
while (e.MoveNext())
{
if (e.Key.ToString().IndexOf(k, StringComparison.OrdinalIgnoreCase) != -1)
{
Remove(e.Key.ToString());
}
}
}
}
///
/// 移出所有Cache
///
public static void RemoveAll()
{
var e = cache.GetEnumerator();
while (e.MoveNext())
{
Remove(e.Key.ToString());
}
}
///
/// 获取所有key
///
///
public static List GetKeys()
{
List list = new List();
var e = cache.GetEnumerator();
while (e.MoveNext())
{
list.Add(e.Key.ToString());
}
return list;
}
///
/// cache总数
///
///
public static int Count()
{
return cache.Count;
}
}
}