1.判断是否有此key的值.类库(CacheHelper)
注:如果要获取缓存数据,请使用TryGetValue方法
public static bool Contains(string key)
{
if (HttpRuntime.Cache[key] != null)
{
return true;
}
else
{
return false;
}
}
2.通过缓存键获取相应的内容
public static T Get<T>(string key)
{
return (T)HttpRuntime.Cache[key];
}
3.新增,添加缓存(如果缓存键已经存在,则此方法调用无效)
public static void Set<T>(string key, T value, TimeSpan tspan)
{
HttpRuntime.Cache.Add(key, value, null, DateTime.Now.Add(tspan),
TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
}
//redis运行时缓存设置
public static T GetSetRuntimeCache<T>(string key, Func<T> act, TimeSpan? timeSpan)
{
if (CacheHelper.Contains(key))
{
return CacheHelper.Get<T>(key);
}
var obj = act();
if (timeSpan != TimeSpan.Zero)
{
CacheHelper.Set(key, obj, timeSpan.Value);
}
return obj;
}