原文:
.NET Core MemoryCache缓存获取全部缓存键
在Core中不能使用原HttpRuntime.Cache缓存,改为MemoryCache(Microsoft.Extensions.Caching.Memory).
现MemoryCache新版为2.0.1,于原HttpRuntime.Cache扩展方法基本相同,但里面没有查询全部键(key) 的扩展,要想查询可通过反射查找
代码如下:
public List<string> GetCacheKeys() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache); var cacheItems = entries as IDictionary; var keys = new List<string>(); if (cacheItems == null) return keys; foreach (DictionaryEntry cacheItem in cacheItems) { keys.Add(cacheItem.Key.ToString()); } return keys; }
这样我们就能获取到全部的键.
整体MemoryCacheHelper类如下:


public class MemoryCacheHelper { private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions()); /// <summary> /// 验证缓存项是否存在 /// </summary> /// <param name="key">缓存Key</param> /// <returns></returns> public bool Exists(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); return Cache.TryGetValue(key, out