using System; using System.Collections.Generic; using System.Runtime.Caching; namespace IStation { /// /// 内存缓存辅助类 /// public class MemoryCacheHelper { //缓存对象 private static SharedMemoryCache MemoryCache { get { return SharedMemoryCache.Instance; } } /// /// 设置缓存 /// /// /// /// 多少秒后移除缓存项 public static void Set(string key, object obj, int second = 300) { var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(second)); MemoryCache.Set(key, obj, policy); } /// /// 获取缓存 /// /// /// /// public static T Get(string key) { return MemoryCache.Get(key); } /// /// 获取和设置 /// /// /// /// /// public static T GetSet(string key, Func func, int second = 300) { var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(second)); return MemoryCache.GetSet(key, func, policy); } /// /// 移除缓存 /// /// public static void Remove(string key) { MemoryCache.Remove(key); } /// /// 移除符合条件的缓存 /// /// public static void Remove(Func keyFunction) { MemoryCache.Remove(keyFunction); } /// /// 移除符合条件的缓存 /// /// public static int Remove(IEnumerable keys) { return MemoryCache.Remove(keys); } /// /// /// /// /// public static int Remove_StartWith(string key) { return MemoryCache.Remove_StartWith(key); } } }