[笔记] ASP.NET本身的缓存实现机制,基于Cache的实现。提供按分类进行管理的缓存功能
Posted on 2008-08-28 14:34 AndyZhou 阅读(286) 评论(0) 编辑 收藏 举报
1. 申明一个Cache
private static Cache cache = HttpRuntime.Cache;
2. 往Cache内插入值
cache.Insert(CreateKey(category, key), value, null, Cache.NoAbsoluteExpiration, TimeSpan.Zero);
3 读取Cache类的值
/// <summary>
/// 获取缓存项
/// </summary>
/// <param name="category">缓存所属分类</param>
/// <param name="key">键</param>
/// <returns>缓存项</returns>
public static object GetValue(string category, string key)
{
return cache[CreateKey(category, key)];
}
4 清除Cache内的值
//全部清除Cache内的值
if (cache.Count == 0)
{
//没有缓存项,直接返回
return;
}
lock (cache)
{
List<string> list = new List<string>();
var enumerator = cache.GetEnumerator();
string key = null;
while (enumerator.MoveNext())
{
key = enumerator.Key.ToString();
list.Add(key);
}
list.ForEach(item => cache.Remove(item));
}
//清除指定的Cache内的值
lock (cache)
{
var enumerator = cache.GetEnumerator();
List<string> list = new List<string>(cache.Count);
string key = null;
while (enumerator.MoveNext())
{
key = enumerator.Key.ToString();
if (key.StartsWith(start))
{
//以所属分类作为开头的键符合清除条件
list.Add(key);
}
}
list.ForEach(item => cache.Remove(item));
}