using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Configuration;
namespace xxx.Website.Portal.Web.Common
{
public class CacheHelper
{
public static Cache Cache
{
get { return HttpContext.Current.Cache; }
}
public static void CacheData(string key, object data, string type) {
if (data == null) return;
// double CacheDuration = 0;
if (type == "RemainingTime") {
DateTime d1 = DateTime.Today.AddDays(1);
//DateTime d2 = DateTime.Now;
//TimeSpan ts = d1.Subtract(d2).Duration();
//CacheDuration = ts.TotalMinutes;
// if (CacheDuration > 0)
CacheHelper.Cache.Insert(key, data, null, d1, TimeSpan.Zero);
// CacheHelper.Cache.Insert(key, data, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero);
}
}
public static void CacheData(string key, object data)
{
if (data == null) return;
double CacheDuration = 0;
if (!double.TryParse(ConfigurationManager.AppSettings["Cache"], out CacheDuration))
CacheDuration = 10;
if (CacheDuration > 0)
CacheHelper.Cache.Insert(key, data, null,
DateTime.Now.AddMinutes(CacheDuration), TimeSpan.Zero);
}
public static void Remove(string key)
{
Cache.Remove(key);
}
public static object GetData(string key)
{
return Cache.Get(key);
}
/// <summary>
/// 删除Cache中,以指定字符串开头的所有缓存项
/// </summary>
/// <param name="prefix"></param>
public static void PurgeCacheItems(string prefix)
{
prefix = prefix.ToLower();
List<string> itemsToRemove = new List<string>();
IDictionaryEnumerator enumerator = CacheHelper.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Key.ToString().ToLower().StartsWith(prefix))
itemsToRemove.Add(enumerator.Key.ToString());
}
foreach (string itemToRemove in itemsToRemove)
CacheHelper.Cache.Remove(itemToRemove);
}
public static void Clear()
{
List<string> cacheKeys = new List<string>();
IDictionaryEnumerator cacheEnum = CacheHelper.Cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
cacheKeys.Add(cacheEnum.Key.ToString());
}
foreach (string cacheKey in cacheKeys)
{
CacheHelper.Cache.Remove(cacheKey);
}
}
}
}