using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; namespace TelpoPush.Service.Cache { internal class MemoryCacheUtil { static MemoryCache cache = new MemoryCache(new MemoryCacheOptions()); /// /// 创建缓存项的文件 /// /// 缓存Key /// object对象 public static void Set(string key, object value) { if (key != null) { cache.Set(key, value); } } /// /// 创建缓存项过期 /// /// 缓存Key /// object对象 /// 过期时间(秒) public static void Set(string key, object value, int expires) { if (key != null) { cache.Set(key, value, new MemoryCacheEntryOptions() //设置缓存时间,如果被访问重置缓存时间。设置相对过期时间x秒 .SetSlidingExpiration(TimeSpan.FromSeconds(expires))); } } /// /// 获取缓存对象 /// /// 缓存Key /// object对象 public static object Get(string key) { object val = null; if (key != null && cache.TryGetValue(key, out val)) { return val; } else { return default(object); } } /// /// 获取缓存对象 /// /// T对象 /// 缓存Key /// public static T Get(string key) { object obj = Get(key); return obj == null ? default(T) : (T)obj; } /// /// 移除缓存项的文件 /// /// 缓存Key public static void Remove(string key) { cache.Remove(key); } } }