浅谈cache的不正确用法

fanliang11 fanliang11 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
有很多程序员都用cache对象进行数据缓存.想必大家都是这样写的吧,cache.Insert ("temp", value).你们想没想过设置缓存失效时间.其实正确的写法也就是
 cache.Add("temp", value, null,DateTime.Now.AddMinutes(60), TimeSpan.Zero, CacheItemPriority.High, null);

每次写怎么一长串代码是不是很累..其实可以偷懒写个通用缓存类,代码如下:

///<summary>
//作用:缓存
///作者: 范亮(fanliang11)转贴请注明原作者
///编写日期: 2008-6-13
///</summary>
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Data;

namespace test
{
/// <summary>
/// 缓存类

/// </summary>
public class CommonCache
{
#region 构造函数
/// <summary>
/// 静态构造函数
/// </summary>
static CommonCache()
{
}
#endregion


#region 属性定义
/// <summary>
/// 失效时间单位为分钟
/// </summary>
public static int LoseTime
{
set
{
mLoseTime = value;
}
}


#endregion


#region 公共方法

/// <summary>
/// 获取值
/// </summary>
/// <param name="pKey">键值名</param>
/// <returns>返回键值</returns>
public static object GetValue(object pKey)
{
object retValue = null;
lock (mCache.SyncRoot)
{
try
{
if (mCache.ContainsKey(pKey))
{
retValue=mCache[pKey];
IList<object> valueArr = (IList<object>)retValue;
DateTime dt = Convert.ToDateTime(valueArr[0]);
if (dt.CompareTo(DateTime.Now) < 0)
{
retValue = null;
}
else
{
retValue = valueArr[1];
}

}
else
{
retValue = null;
}
}
catch (Exception e)
{
retValue = null;
}
}
return retValue;
}


/// <summary>
/// 设置值
/// </summary>
/// <param name="pKey">键值名</param>
/// <param name="pValue">键值</param>
public static void SetValue(object pKey, object pValue)
{
IList<object> valueArr = new List<object>() ;
valueArr.Add (DateTime.Now.AddMinutes(mLoseTime));
valueArr.Add ( pValue);

lock (mCache.SyncRoot)
{
try
{
if (!mCache.ContainsKey(pKey))
{
mCache.Add(pKey, valueArr);
}
else
{
mCache[pKey] = valueArr;
}
}
catch (Exception e)
{
}
}
}
#endregion


#region 字段定义
/// <summary>
/// 缓存对象
/// </summary>
private static Hashtable mCache = new Hashtable();

/// <summary>
/// 失效时间(单位:分钟)
/// </summary>
private static int mLoseTime = 60;
#endregion
}
}

大家有什么其它的好方法可以写出来..如对程序有任何意见..请联系作者QQ:137629448
...全文
评论 50
收藏 已收藏
分享
返回顶部
fanliang11
.NET社区 62,272 成员 668,968 内容