代码改变世界

asp.net 数据缓存

2012-03-05 16:46  xtsjh0001  阅读(214)  评论(0编辑  收藏  举报

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 Website.Util
{
public static class CacheHelper
{
public static Cache Cache
{
get { return HttpContext.Current.Cache; }
}
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 GetDate(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);
}
}

}
}


调用方法

string cachekey = string.Format("model_{0}_{1}", sort,language);
var list = CacheHelper.GetDate(cachekey) as List<model>;
if (list == null) {
list= entity.model.ToList();
CacheHelper.CacheData(cachekey, list);
}