using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Helpers { /// /// 公共缓存类 /// public static class CacheHelper { private static ObjectCache cache = System.Runtime.Caching.MemoryCache.Default; /// /// 查询缓存是否存在 /// /// 缓存键 /// 是否存在 public static bool ExistsCache(string key) { return cache.Contains(key); } /// /// 根据缓存键移除缓存对象 /// /// 对象类型 /// 缓存键 public static void RemoveCache(string key) where T : class { if (!cache.Contains(key)) return; var model = GetCache(key); foreach (var a in model.GetType().GetProperties()){ a.SetValue(model,""); } SetCache(key, model, 1); cache.Remove(key); } /// /// 设置缓存对象 /// /// 对象类型 /// 缓存键 /// 缓存对象 /// 过期时间(单位:分钟,默认值30) public static void SetCache(string key, T obj, double expires = 30) where T : class { DateTimeOffset cc = DateTimeOffset.Now.AddMinutes(expires); cache.Set(key, obj, cc); } /// /// 根据缓存键获取缓存对象 /// /// 对象类型 /// 缓存键 /// 缓存对象 public static T GetCache(string key) where T : class { if (!cache.Contains(key)) return null; var item = cache.GetCacheItem(key); if (item != null) { return item.Value as T; } return null; } /// /// 获取缓存对象,如果不存在,则重新设置 /// /// 对象类型 /// 缓存键 /// 缓存委托 /// 过期时间(单位:分钟,默认值30) /// 缓存对象 public static T GetCache(string key, Func func, double expires = 30) where T : class { if (!cache.Contains(key)) { CacheItemPolicy policy = new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(expires) }; T obj = null; if (func != null) { obj = func(); if (obj != null) { cache.Set(key, obj, policy); } } return obj; } else { return cache.GetCacheItem(key).Value as T; }; } } }