dotnet 核心中的内存缓存 [英] Memory Cache in dotnet core
问题描述
我正在尝试编写一个类来处理 .net 核心类库中的内存缓存.如果我不使用核心,那么我可以写
I am trying to write a class to handle Memory cache in a .net core class library. If I use not the core then I could write
using System.Runtime.Caching;
using System.Collections.Concurrent;
namespace n{
public class MyCache
{
readonly MemoryCache _cache;
readonly Func<CacheItemPolicy> _cachePolicy;
static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();
public MyCache(){
_cache = MemoryCache.Default;
_cachePolicy = () => new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(15),
RemovedCallback = x =>
{
object o;
_theLock.TryRemove(x.CacheItem.Key, out o);
}
};
}
public void Save(string idstring, object value){
lock (_locks.GetOrAdd(idstring, _ => new object()))
{
_cache.Add(idstring, value, _cachePolicy.Invoke());
}
....
}
}
}
在 .Net 核心中我找不到 System.Runtime.Cache.在阅读了 .net core In Memory Cache 后,我添加了参考 Microsoft.Extensions.Caching.Memory (1.1.0) 并尝试
Within .Net core I could not find System.Runtime.Cache. After reading the .net core In Memory Cache, I have added reference Microsoft.Extensions.Caching.Memory (1.1.0) and tried
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;
namespace n
{
public class MyCache
{
readonly MemoryCache _cache;
readonly Func<CacheItemPolicy> _cachePolicy;
static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();
public MyCache(IMemoryCache memoryCache){
_cache = memoryCache;// ?? **MemoryCache**;
}
public void Save(string idstring, object value){
lock (_locks.GetOrAdd(idstring, _ => new object()))
{
_cache.Set(idstring, value,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(15))
.RegisterPostEvictionCallback(
(key, value, reason, substate) =>
{
object o;
_locks.TryRemove(key.ToString(), out o);
}
));
}
....
}
}
}
希望 save 方法中的代码没问题,尽管目前我的大部分 mycache 测试都失败了.任何人都可以指出什么是错的吗?主要问题是关于构造函数我应该怎么做来设置缓存而不是 MemoryCache.Default
Hope code inside the save method is ok, although most of my mycache tests are failing at the moment. Can anyone please point out what is wrong? The main question is about the constructor What should i do to set the cache instead MemoryCache.Default
_cache = memoryCache ?? MemoryCache.Default;
推荐答案
构造函数为:
using Microsoft.Extensions.Caching.Memory;
...
MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());
这篇关于dotnet 核心中的内存缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!