using System;
using System.Web;
using System.Web.Caching;
namespace net91com.Common
{
/// <summary>
/// CacheHelper 的摘要说明。
/// </summary>
public class CacheHelper
{
private CacheHelper()
{
}
/// <summary>
/// AddCache 添加Cache,缓存存在则添加失败
/// </summary>
/// <param name="keyValue">键</param>
/// <param name="objValue">值</param>
/// <param name="tsNum">tsNum 秒</param>
public static void Add(string keyValue, object objValue, double seconds)
{
System.Web.HttpRuntime.Cache.Add(keyValue, objValue, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero, CacheItemPriority.Default, null);
}
/// <summary>
/// InsertCache 添加Cache,缓存如果存在则会替换
/// </summary>
/// <param name="keyValue">键</param>
/// <param name="objValue">值</param>
/// <param name="tsNum">tsNum 秒</param>
public static void Insert(string keyValue, object objValue, double seconds)
{
System.Web.HttpRuntime.Cache.Insert(keyValue, objValue, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero, CacheItemPriority.Default, null);
}
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="keyValue">缓存键</param>
public static void Remove(string keyValue)
{
System.Web.HttpRuntime.Cache.Remove(keyValue);
}
/// <summary>
/// 判断是否存在缓存
/// </summary>
/// <param name="keyValue">缓存键</param>
/// <returns></returns>
public static bool Exist(string keyValue)
{
return System.Web.HttpRuntime.Cache[keyValue] != null;
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="keyValue">keyValue</param>
/// <returns></returns>
public static object Get(string keyValue)
{
return System.Web.HttpRuntime.Cache[keyValue];
}
#region 获取缓存内容
/// <summary>
/// 获取缓存内容
/// </summary>
/// <param name="cacheKey">缓存标识</param>
/// <returns></returns>
public static T Get<T>(string cacheKey)
{
return (T)HttpRuntime.Cache[cacheKey];
}
#endregion
#region 添加缓存
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="cacheKey">缓存标识</param>
/// <param name="cacheObj">缓存对象</param>
/// <param name="milliseconds">缓存的时间(以秒位单位)</param>
/// <returns></returns>
public static bool Add<T>(string cacheKey, T cacheObj, double seconds)
{
try
{
HttpRuntime.Cache.Add(
cacheKey,
cacheObj,
null,
DateTime.Now.AddSeconds(seconds),
TimeSpan.Zero,
CacheItemPriority.Normal,
null
);
return true;
}
catch//(Exception ex)
{
return false;
}
}
public static bool Add<T>(string cacheKey, T cacheObj, DateTime expireTime)
{
try
{
HttpRuntime.Cache.Add(
cacheKey,
cacheObj,
null,
expireTime,
TimeSpan.Zero,
CacheItemPriority.Normal,
null
);
return true;
}
catch//(Exception ex)
{
return false;
}
}
#endregion
}
}