using System; using System.Runtime.Caching; namespace SHJX.Service.Common.CustomUtil { /// /// 数据缓存工具类 /// public static class DataCache { private static readonly MemoryCache cache = new("ErrorFromEmsCache"); /// /// 在缓存中新增数据 /// /// public static void Set(string key, T value) { var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddHours(15) }; if (!Contains(key)) { cache.Set(key, value, policy); } cache[key] = value; } /// /// 查询缓存中是否包含指定键 /// /// /// public static bool Contains(string key) { return cache.Contains(key); } /// /// 获取缓存中数据 /// /// /// public static T Get(string key) { try { if (Contains(key)) { return (T)cache[key]; } return default; } catch (Exception) { return default; } } /// /// 移除缓存中的数据 /// /// public static void Remove(string key) { if (Contains(key)) { cache.Remove(key); } } } }