浅谈cache的不正确用法
有很多程序员都用cache对象进行数据缓存.想必大家都是这样写的吧,cache.Insert ("temp", value).你们想没想过设置缓存失效时间.其实正确的写法也就是
每次写怎么一长串代码是不是很累..其实可以偷懒写个通用缓存类,代码如下:
大家有什么其它的好方法可以写出来..如对程序有任何意见..请联系作者QQ:137629448
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
...全文
相关推荐
浅谈cache memory
介绍CPU硬件cache的一本书,国内写的较好的资料
浅谈cache memory 王齐.pdf
主要讲解x86架构下的cache的怎么工作原理和怎么实现等,说的很详细,水平很高的,但是要有相应的知识才能看明白,作者是王齐,
cache一致性和cache不一致的解决方法
本文通过对Cache相关内容的介绍阐述了Cache一致性问题。
浅谈Spring boot cache使用和原理
主要介绍了浅谈Spring boot cache使用和原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
nginx cache不缓存问题的原因与解决方案
nginx.conf 部分内容: proxy_temp_path /nginx/cache/temp; proxy_cache_path /nginx/cache/path levels=1:2 keys_zone=cache_test:2048m inactive=7d max_size=10g; ...... location ~ .(gif|jpg|jgep|png)$ { proxy_pass http://upstreams; proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-


