using System; using System.Collections.Concurrent; using System.Linq; namespace PCRobot.Utils { /// /// 本地缓存 /// public class CacheHelper { private static DateTime _nextRemoveDatetime = DateTime.Now.AddMinutes(30); /// /// 删除 过期 /// private static void RemoveTimeOut() { if (DateTime.Now < _nextRemoveDatetime) { return; } var array = _caches.Values.ToArray().Where(w => w.ExpirationTime < DateTime.Now).ToArray(); foreach (var v in array) { _caches.TryRemove(v.Key, out _); } _nextRemoveDatetime = DateTime.Now.AddMinutes(30); } private class CacheItem { /// /// 缓存KEY /// public string Key { get; set; } /// /// 过期时间 /// public DateTime ExpirationTime { get; set; } /// /// 对象 /// public object Object { get; set; } } private static readonly ConcurrentDictionary _caches = new ConcurrentDictionary(); /// /// 重置缓存,让这个程序的缓存全部失效 /// public static void ResetCache() { _caches.Clear(); } /// /// 增加缓存 /// /// key /// 值 /// 值(秒) public static bool Add(string key, object value, int time = 60) { _caches.AddOrUpdate(key, (k) => { return new CacheItem() { Key = k, Object = value, ExpirationTime = time < 0 ? DateTime.MaxValue : DateTime.Now.AddSeconds(time) }; }, (k, v) => { v.Object = value; v.ExpirationTime = time < 0 ? DateTime.MaxValue : DateTime.Now.AddSeconds(time); return v; }); return true; } /// /// 获取缓存数据(如果不存在返回默认值) /// /// /// /// public static T Get(string key) { if (string.IsNullOrWhiteSpace(key)) { return default(T); } if (_caches.TryGetValue(key, out var result)) { if (result.ExpirationTime < DateTime.Now) { _caches.TryRemove(key, out _); return default(T); } return (T)result.Object; } return default(T); } /// /// 获取缓存 /// /// key /// public static object GetValue(string key) { RemoveTimeOut(); if (string.IsNullOrWhiteSpace(key)) { return null; } if (_caches.TryGetValue(key, out var result)) { if (result.ExpirationTime < DateTime.Now) { _caches.TryRemove(key, out _); return null; } return result.Object; } return null; } /// /// 获取缓存,不存在则新增 /// /// /// /// /// /// /// public static T GetValueOrAdd(string key, Func defFunc, int time = 60) where T : class { if (string.IsNullOrWhiteSpace(key)) { throw new Exception("缓存key不能为空"); } if (string.IsNullOrWhiteSpace(key)) { return null; } if (_caches.TryGetValue(key, out var result)) { if (result.ExpirationTime > DateTime.Now) { _caches.TryRemove(key, out _); var obj = defFunc(); Add(key, obj, time); return obj; } return (T)result.Object; } else { var obj = defFunc(); Add(key, obj, time); return obj; } } /// ///移除缓存 /// /// public static void Remove(string key) { _caches.TryRemove(key, out _); } public static bool Exist(string key) { return _caches.ContainsKey(key); } } }