我正在使用新的.NET 4.0缓存命名空间:System.Runtime.Caching
。
现在,我只是在做一些原型/摆弄新API,以便找到最适合真实应用的。
与此一致,我正在尝试创建一个基本上转储缓存中所有内容的页面(ASP.NET MVC),尤其是以下信息:
但是,除了键/对象之外,我似乎无法获得任何东西。
这是我正在玩的代码:
public ActionResult Index()
{
var cache = MemoryCache.Default;
// i can get the list of cache keys like this:
var cacheKeys = cache.Select(kvp => kvp.Key).ToList();
// i can also get a strongly-typed "CacheItem" like this:
CacheItem item = cache.GetCacheItem("someKey");
}
我希望“CacheItem”类会暴露我需要的信息(到期,依赖等等 - 至少作为“getters”)。
但事实并非如此。它拥有的只是键,值和区域名称的属性。
如何检查缓存中的项目并吐出我需要的信息?
是否缺少名称空间/类?
修改
看起来有一个 ChangeMonitor 类,但是再次 - 这不会给出过期信息,它只允许您在删除缓存项时订阅事件。
必须才能抓取缓存中的项目,以及它们何时到期。
编辑2
不知道这是否应该是一个单独的问题,而且 - 我对我应该给我的ObjectCache的生命周期感到困惑。 MSDN说它不是单例,你实际上可以创建多个ObjectCache实例。这意味着什么,我必须在访问ObjectCache实例时使用完全锁定的单例?
答案 0 :(得分:9)
我不认为有一种方法可以在CacheItemPolicy添加到缓存集合后检索它。
解决此问题的最佳方法是将策略对象与要缓存的项目一起缓存,只需将“策略”附加到密钥名称,以便以后可以检索策略。这显然假设您可以控制首先将项目实际添加到缓存中。示例如下:
public ActionResult Index()
{
string key = "Hello";
string value = "World";
var cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now.AddDays(1);
cache.Add(new CacheItem(key, value), policy);
cache.Add(new CacheItem(key + "Policy", policy), null);
CacheItem item = cache.GetCacheItem(key);
CacheItem policyItem = cache.GetCacheItem(key + "Policy");
CacheItemPolicy policy2 = policyItem.Value as CacheItemPolicy;
ViewBag.Message = key + " " + value;
return View();
}
答案 1 :(得分:0)
我最近不得不为MemoryCache
包装器创建单元测试。我想检查包装程序是否使用预期的策略添加到基础缓存中。
我想出了以下GetCacheItemPolicy
扩展方法,该方法大量使用反射。即使我的目的只是对包装器进行单元测试,我还是尝试优化每个反射,以使其在其他对性能至关重要的环境中可用(即使您在生产代码中进行此操作,最可能的性能也不重要,但是嘿...)。
internal static class MemoryCacheExtensions
{
static MemoryCacheExtensions()
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Expression<Func<Func<object, object>>> createGetterExpression = () => CreateObjectGetter<object, object>(null);
var genericCreateObjectGetterMethodInfo = ((MethodCallExpression)createGetterExpression.Body).Method.GetGenericMethodDefinition();
// Basic types
var memoryCacheType = typeof(MemoryCache);
var getEntryMethodInfo = memoryCacheType.GetMethod("GetEntry", flags);
// MemoryCacheEntry fields
Debug.Assert(getEntryMethodInfo != null, nameof(getEntryMethodInfo) + " != null");
var memoryCacheEntryType = getEntryMethodInfo.ReturnType;
var valueFieldInfo = memoryCacheEntryType.GetField("_value", flags);
var usageBucketFieldInfo = memoryCacheEntryType.GetField("_usageBucket", flags);
var removedCallbackFieldInfo = memoryCacheEntryType.GetField("_callback", flags);
var seldomUsedFieldsFieldInfo = memoryCacheEntryType.GetField("_fields", flags);
var slidingExpirationFieldInfo = memoryCacheEntryType.GetField("_slidingExp", flags);
var absoluteExpirationFieldInfo = memoryCacheEntryType.GetField("_utcAbsExp", flags);
// SeldomUsedFields fields
Debug.Assert(seldomUsedFieldsFieldInfo != null, nameof(seldomUsedFieldsFieldInfo) + " != null");
var seldomUsedFieldsType = seldomUsedFieldsFieldInfo.FieldType;
var dependenciesFieldInfo = seldomUsedFieldsType.GetField("_dependencies", flags);
// SentinelEntry fields
var sentinelEntryType = memoryCacheType.GetNestedType("SentinelEntry", flags);
var updateCallbackFieldInfo = sentinelEntryType.GetField("_updateCallback", flags);
GetMemoryCacheEntry = (Func<MemoryCache, string, object>)Delegate
.CreateDelegate(typeof(Func<MemoryCache, string, object>), getEntryMethodInfo);
Debug.Assert(valueFieldInfo != null, nameof(valueFieldInfo) + " != null");
GetMemoryCacheEntryValue = (Func<object, object>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, valueFieldInfo.FieldType)
.Invoke(null, new object[] { valueFieldInfo });
Debug.Assert(usageBucketFieldInfo != null, nameof(usageBucketFieldInfo) + " != null");
GetMemoryCacheEntryUsageBucket = (Func<object, byte>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, usageBucketFieldInfo.FieldType)
.Invoke(null, new object[] { usageBucketFieldInfo });
Debug.Assert(removedCallbackFieldInfo != null, nameof(removedCallbackFieldInfo) + " != null");
GetMemoryCacheEntryRemovedCallback = (Func<object, CacheEntryRemovedCallback>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, removedCallbackFieldInfo.FieldType)
.Invoke(null, new object[] { removedCallbackFieldInfo });
GetMemoryCacheEntrySeldomUsedFields = (Func<object, object>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, seldomUsedFieldsFieldInfo.FieldType)
.Invoke(null, new object[] { seldomUsedFieldsFieldInfo });
Debug.Assert(slidingExpirationFieldInfo != null, nameof(slidingExpirationFieldInfo) + " != null");
GetMemoryCacheEntrySlidingExpiration = (Func<object, TimeSpan>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, slidingExpirationFieldInfo.FieldType)
.Invoke(null, new object[] { slidingExpirationFieldInfo });
Debug.Assert(absoluteExpirationFieldInfo != null, nameof(absoluteExpirationFieldInfo) + " != null");
GetMemoryCacheEntryAbsoluteExpiration = (Func<object, DateTime>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(memoryCacheEntryType, absoluteExpirationFieldInfo.FieldType)
.Invoke(null, new object[] { absoluteExpirationFieldInfo });
Debug.Assert(dependenciesFieldInfo != null, nameof(dependenciesFieldInfo) + " != null");
GetSeldomUsedFieldsDependencies = (Func<object, Collection<ChangeMonitor>>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(seldomUsedFieldsType, dependenciesFieldInfo.FieldType)
.Invoke(null, new object[] { dependenciesFieldInfo });
Debug.Assert(updateCallbackFieldInfo != null, nameof(updateCallbackFieldInfo) + " != null");
GetSentinelEntryUpdateCallback = (Func<object, CacheEntryUpdateCallback>)genericCreateObjectGetterMethodInfo
.MakeGenericMethod(sentinelEntryType, updateCallbackFieldInfo.FieldType)
.Invoke(null, new object[] { updateCallbackFieldInfo });
}
private static Func<MemoryCache, string, object> GetMemoryCacheEntry { get; }
private static Func<object, object> GetMemoryCacheEntryValue { get; }
private static Func<object, byte> GetMemoryCacheEntryUsageBucket { get; }
private static Func<object, CacheEntryRemovedCallback> GetMemoryCacheEntryRemovedCallback { get; }
private static Func<object, object> GetMemoryCacheEntrySeldomUsedFields { get; }
private static Func<object, TimeSpan> GetMemoryCacheEntrySlidingExpiration { get; }
private static Func<object, DateTime> GetMemoryCacheEntryAbsoluteExpiration { get; }
private static Func<object, Collection<ChangeMonitor>> GetSeldomUsedFieldsDependencies { get; }
private static Func<object, CacheEntryUpdateCallback> GetSentinelEntryUpdateCallback { get; }
public static CacheItemPolicy GetCacheItemPolicy(this MemoryCache memoryCache, string key)
{
var entry = GetMemoryCacheEntry(memoryCache, key);
if (entry == null) return null;
var sentinel = GetMemoryCacheEntry(memoryCache, "OnUpdateSentinel" + key);
var sentinelValue = sentinel == null ? null : GetMemoryCacheEntryValue(sentinel);
var usageBucket = GetMemoryCacheEntryUsageBucket(entry);
var slidingExpiration = GetMemoryCacheEntrySlidingExpiration(entry);
var absoluteExpiration = GetMemoryCacheEntryAbsoluteExpiration(entry);
var seldomUsedFields = GetMemoryCacheEntrySeldomUsedFields(entry);
var changeMonitors = seldomUsedFields == null ? null : GetSeldomUsedFieldsDependencies(seldomUsedFields);
var removedCallback = GetMemoryCacheEntryRemovedCallback(entry);
var updatedCallback = sentinelValue == null ? null : GetSentinelEntryUpdateCallback(sentinelValue);
var cacheItemPolicy = new CacheItemPolicy
{
Priority = usageBucket == 0xFF ? CacheItemPriority.NotRemovable : CacheItemPriority.Default,
AbsoluteExpiration = absoluteExpiration,
RemovedCallback = removedCallback,
SlidingExpiration = slidingExpiration,
UpdateCallback = updatedCallback,
};
if (changeMonitors != null)
{
foreach (var changeMonitor in changeMonitors)
{
cacheItemPolicy.ChangeMonitors.Add(changeMonitor);
}
}
return cacheItemPolicy;
}
private static Func<TTarget, TFieldType> CreateGetter<TTarget, TFieldType>(FieldInfo field)
{
var fieldReflectedType = field.ReflectedType;
Debug.Assert(fieldReflectedType != null, "field.ReflectedType != null");
var methodName = fieldReflectedType.FullName + ".get_" + field.Name;
var getterMethod = new DynamicMethod(methodName, typeof(TFieldType), new[] { typeof(TTarget) }, true);
var generator = getterMethod.GetILGenerator();
if (field.IsStatic)
{
generator.Emit(OpCodes.Ldsfld, field);
}
else
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, field);
}
generator.Emit(OpCodes.Ret);
return (Func<TTarget, TFieldType>)getterMethod.CreateDelegate(typeof(Func<TTarget, TFieldType>));
}
private static Func<object, TFieldType> CreateObjectGetter<TTarget, TFieldType>(FieldInfo fieldInfo)
{
var getter = CreateGetter<TTarget, TFieldType>(fieldInfo);
return @object => getter((TTarget)@object);
}
}