using System.Timers; using Timer = System.Timers.Timer; namespace VberZero.Tools.CacheHelpers; /// /// 缓存 /// public abstract class InfoCache where T : class, new() { //public static InfoCache Instance = new InfoCache(); protected InfoCache() { Timer = new Timer(); ExpireInterval = 60 * 2; ClearInterval = 30; StartClear(); } /// /// /// /// 缓存过期时间(分钟)默认120分钟 /// 缓存清理间隔(分钟)默认30分钟 protected InfoCache(int? expireInterval, int? clearInterval) { Timer = new Timer(); ExpireInterval = expireInterval ?? 60 * 2; ClearInterval = clearInterval ?? 30; StartClear(); } protected void StartClear() { StopClear(); if (!HasStarted) { Timer.Enabled = true; Timer.Interval = 1000 * 60 * ClearInterval; Timer.Start(); Timer.Elapsed += CheckOverTime; HasStarted = true; } } protected void StopClear() { if (HasStarted) { Timer.Stop(); Timer.Elapsed -= CheckOverTime; HasStarted = false; } } public bool HasStarted; /// /// 缓存清理间隔(分钟) /// protected int ClearInterval { get; set; } /// /// 缓存过期时间(分钟) /// protected int ExpireInterval { get; set; } /// /// 尝试获取缓存 /// /// /// /// public virtual bool TryGetCache(string key, out T? value) { value = default(T); if (Caches.ContainsKey(key)) { InfoWithDate valueWithDate = Caches[key]; value = valueWithDate.GroupInfo; valueWithDate.ActiveTime = DateTime.Now; return true; } return false; } /// /// 添加缓存 /// /// /// public virtual void AddCache(string key, T value) { if (Caches.ContainsKey(key)) { Caches[key] = new InfoWithDate(value); } else { Caches.Add(key, new InfoWithDate(value)); } } /// /// 移除缓存 /// /// public virtual void RemoveCache(string key) { if (Caches.ContainsKey(key)) { Caches.Remove(key); } } /// /// 清除所有缓存信息 /// public virtual void ClearCache() { Caches.Clear(); } private Timer Timer { get; } private void CheckOverTime(object? source, ElapsedEventArgs e) { Dictionary temp = new Dictionary(); foreach (var cache in Caches) { if (cache.Value.ActiveTime.CompareTo(DateTime.Now.AddMinutes(-ExpireInterval)) >= 0) { temp.Add(cache.Key, cache.Value); } } lock (Caches) { Caches = temp; } } private static Dictionary Caches { get; set; } = new Dictionary(); private class InfoWithDate { public InfoWithDate(T? value) { ActiveTime = DateTime.Now; GroupInfo = value; } public DateTime ActiveTime { get; set; } public T? GroupInfo { get; } } }