using System;
using System.Web;
using System.Web.Caching;
using System.Collections;
using System.Text.RegularExpressions;
namespace HH.WMS.Utils
{
///
///
/// 常用工具类——缓存类
/// --------------------------------------------------------------------------------
/// SetCache:设置当前应用程序指定CacheKey的Cache值[ +2方法重载 ]
/// GetCache:获取当前应用程序指定CacheKey的Cache值
/// RemoveCache:删除缓存
///
public class ZCache
{
static Cache GetCacheObject()
{
HttpContext context = HttpContext.Current;
if (context != null)
{
return context.Cache;
}
else
{
return HttpRuntime.Cache;
}
}
#region 设置当前应用程序指定CacheKey的Cache值
///
/// 设置当前应用程序指定CacheKey的Cache值
///
/// 键
///
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = GetCacheObject();
objCache.Insert(CacheKey, objObject);
}
#endregion
#region 获取当前应用程序指定CacheKey的Cache值
///
/// 获取当前应用程序指定CacheKey的Cache值
///
///
///
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = GetCacheObject();
return objCache[CacheKey];
}
#endregion
#region 设置当前应用程序指定CacheKey的Cache值[带过期时间等参数]
///
/// 设置当前应用程序指定CacheKey的Cache值
///
///
///
/// 可设置为Cache.NoAbsoluteExpiration
/// 可设置为Cache.NoSlidingExpiration
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
System.Web.Caching.Cache objCache = GetCacheObject();
objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
}
#endregion
#region 删除缓存
///
/// 删除缓存
///
///
public static void RemoveCache(string CacheKey)
{
System.Web.Caching.Cache objCache = GetCacheObject();
objCache.Remove(CacheKey);
}
#endregion
///
/// 清空Cash对象
///
public static void Clear()
{
Cache _cache = GetCacheObject();
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
_cache.Remove(key);
}
}
///
/// 根据正则表达式的模式移除Cache
///
/// 模式
public static void RemoveByPattern(string pattern)
{
Cache _cache = GetCacheObject();
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
while (CacheEnum.MoveNext())
{
if (regex.IsMatch(CacheEnum.Key.ToString()))
_cache.Remove(CacheEnum.Key.ToString());
}
}
}
}