using System;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;namespace SpecialSale.Sys.SysCache
{
/// <summary>
/// 缓存过期类型枚举
/// </summary>
public enum EnumCacheExpirationType
{
/// <summary>
/// 绝对过期
/// </summary>
AbsoluteTime = 1,
/// <summary>
/// 固定过期
/// </summary>
SlidingTime = 2,
/// <summary>
/// 指定过期格式,以特定的格式来过期
/// </summary>
ExtendedFormatTime=3,
/// <summary>
/// 文件依赖
/// </summary>
FileDependency=4,
} public static class CacheHelper
{
//2种建立CacheManager的方式
//ICacheManager cache = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>();
private static ICacheManager cache = CacheFactory.GetCacheManager(); /// <summary>
/// 添加缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="type">缓存过期类型</param>
public static void Add(string key, object value, EnumCacheExpirationType type)
{
switch (type)
{
case EnumCacheExpirationType.AbsoluteTime:
cache.Add(key, value, CacheItemPriority.Normal, new SysCacheItemRefreshAction(), new AbsoluteTime(TimeSpan.FromMinutes(15)));
break;
case EnumCacheExpirationType.SlidingTime:
cache.Add(key, value, CacheItemPriority.Normal, new SysCacheItemRefreshAction(), new SlidingTime(TimeSpan.FromMinutes(15)));
break;
case EnumCacheExpirationType.ExtendedFormatTime:
throw new Exception("暂时不支持 ExtendedFormatTime 过期");
break;
case EnumCacheExpirationType.FileDependency:
throw new Exception("暂时不支持 FileDependency 过期");
break;
}
} /// <summary>
/// 获取缓存对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCache<T>(string key) where T:class
{
return cache.GetData(key) as T;
} /// <summary>
/// 移除缓存对象
/// </summary>
/// <param name="key"></param>
public static void RemoveCache(string key)
{
cache.Remove(key);
}
} /// <summary>
/// 自定义缓存刷新操作
/// </summary>
[Serializable]
public class SysCacheItemRefreshAction : ICacheItemRefreshAction
{
#region ICacheItemRefreshAction 成员 /// <summary>
/// 自定义刷新操作
/// </summary>
/// <param name="removedKey">移除的键</param>
/// <param name="expiredValue">过期的值</param>
/// <param name="removalReason">移除理由</param>
void ICacheItemRefreshAction.Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)
{
if (removalReason == CacheItemRemovedReason.Expired)
{
ICacheManager cache = CacheFactory.GetCacheManager();
cache.Add(removedKey, expiredValue);
}
}
#endregion
}
}