using System; using SHJX.Service.Common.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Caching.Memory; namespace SHJX.Service.Common.Utils { /// /// 数据缓存工具类 /// public class DataCache { private static DataCache _cache; private static readonly object obj_lock = new(); private static readonly ILogger Logger = LogFactory.BuildLogger(typeof(DataCache)); private static readonly MemoryCache cache = new(Options.Create(new MemoryCacheOptions())); private DataCache() { } public static DataCache Instance { get { if (_cache is null) { lock (obj_lock) { _cache = new DataCache(); } } return _cache; } } /// /// 新增 /// /// 缓存类型 /// 键 /// 值 /// 缓存时间(秒) public void Set(object key, T value, int cacheTime = 5) { cache.GetOrCreate(key, entry => { entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheTime)); entry.RegisterPostEvictionCallback((key, value, reason, state) => { Logger.LogInformation($"{value}已过期"); }); return value; }); } /// /// 获取缓存中数据 /// /// /// public T Get(object key) { try { if (cache.TryGetValue(key, out var value)) { return (T)value; } return default; } catch (Exception) { return default; } } /// /// 移除缓存中的数据 /// /// public void Remove(object key) { if (cache.TryGetValue(key, out _)) { cache.Remove(key); } } public int Count => cache.Count; } }