我有一个类(它被实例化为单例)包装在ASP.Net的IMemoryCache依赖项中,如下所示:
using Microsoft.Extensions.Caching.Memory;
using System;
namespace Lambgoat.Web.Cache
{
public class CacheStrategy : ICacheStrategy
{
private readonly IMemoryCache _cache;
public CacheStrategy(IMemoryCache cache)
{
_cache = cache;
}
public T Set<T>(string key, T value, DateTimeOffset expiration, int size = 1)
{
var cacheEntryOptions = new MemoryCacheEntryOptions().SetSize(size).SetAbsoluteExpiration(expiration);
return _cache.Set(key, value, cacheEntryOptions);
}
public bool Exists<T>(string id, out T value) where T : new()
{
bool exists = _cache.TryGetValue<T>(id, out T cacheValue);
value = cacheValue ?? new T();
return exists;
}
public void Invalidate(string id) => _cache.Remove(id);
}
}当调用Set()方法时,我想检查缓存总大小是否接近我在Startup.cs中设置的大小限制,如下所示:
if (totalCacheSize + 10 > 1024) {
_cache.Compact(.33);
}我的问题是检索总的缓存大小;如何做这样的事情呢?
发布于 2021-06-23 06:09:27
如果将缓存实例存储为具体的MemoryCache而不是IMemoryCache,则可以访问其唯一的公共属性Count。其他与大小相关的东西都是内部的。
private readonly MemoryCache _cache;
public CacheStrategy(IMemoryCache cache)
{
_cache = (MemoryCache)cache;
}然后检查Count
if (_cache.Count > 1024) {
_cache.Compact(.33);
}由于Count表示条目的数量,因此无法知道它对应的实际内存使用量。
https://stackoverflow.com/questions/68087587
复制相似问题