using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; //不改命名空间,要修改很多地方 namespace ZR.Common { public class CacheHelper { public static MemoryCache Cache { get; set; } private static readonly List _keys; static CacheHelper() { Cache = new MemoryCache(new MemoryCacheOptions { //SizeLimit = 1024 }); _keys = []; } /// /// 获取缓存 /// /// /// /// public static T GetCache(string key) where T : class { if (key == null) throw new ArgumentNullException(nameof(key)); //return Cache.Get(key) as T; //或者 return Cache.Get(key); } /// /// 获取缓存 /// /// /// public static object GetCache(string CacheKey) { return Cache.Get(CacheKey); } public static object Get(string CacheKey) { return Cache.Get(CacheKey); } /// /// 设置缓存,永久缓存 /// /// key /// 值 public static object SetCache(string CacheKey, object objObject) { return Cache.Set(CacheKey, objObject); } /// /// 设置缓存 /// /// key /// 值 /// 过期时间(分钟) public static object SetCache(string CacheKey, object objObject, int Timeout) { return Cache.Set(CacheKey, objObject, DateTime.Now.AddMinutes(Timeout)); } /// /// 设置缓存(秒) /// /// key /// 值 /// 过期时间(秒) public static void SetCaches(string CacheKey, object objObject, int Timeout) { if (!_keys.Contains(CacheKey)) { _keys.Add(CacheKey); } Cache.Set(CacheKey, objObject, DateTime.Now.AddSeconds(Timeout)); } /// /// 设置缓存 /// /// key /// 值 /// 过期时间 /// 过期时间间隔 public static object SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { return Cache.Set(CacheKey, objObject, absoluteExpiration); } /// /// 设定绝对的过期时间 /// /// /// /// 超过多少秒后过期 public static void SetCacheDateTime(string CacheKey, object objObject, long Seconds) { Cache.Set(CacheKey, objObject, DateTime.Now.AddSeconds(Seconds)); } /// /// 删除缓存 /// /// key public static void Remove(string key) { _keys.Remove(key); Cache.Remove(key); } /// /// 验证缓存项是否存在 /// /// 缓存Key /// public static bool Exists(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); return Cache.TryGetValue(key, out _); } /// /// 获取所有缓存键 /// /// //public static List GetCacheKeys() //{ // const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; // //var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache); // //.net7需要这样写 // var coherentState = Cache.GetType().GetField("_coherentState", flags).GetValue(Cache); // var entries = coherentState.GetType().GetField("_entries", flags).GetValue(coherentState); // var keys = new List(); // if (entries is not IDictionary cacheItems) return keys; // foreach (DictionaryEntry cacheItem in cacheItems) // { // keys.Add(cacheItem.Key.ToString()); // //Console.WriteLine("缓存key=" +cacheItem.Key); // } // return keys; //} public static List GetCacheKeys() { return new List(_keys); } // 销毁缓存 public void Dispose() { Cache.Dispose(); } } }