【问题标题】:Memory Cache in dotnet coredotnet core 中的内存缓存
【发布时间】:2017-05-21 05:03:49
【问题描述】:

我正在尝试编写一个类来处理 .net 核心类库中的内存缓存。如果我不使用核心,那么我可以写

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 coreIn Memory Cache之后,我添加了参考Microsoft.Extensions.Caching.Memory (1.1.0) 并尝试了

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

_cache = memoryCache ?? MemoryCache.Default; 

【问题讨论】:

    标签: c# caching .net-core memorycache


    【解决方案1】:

    构造函数是:

    using Microsoft.Extensions.Caching.Memory;
    

    。 . .

    MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());
    

    【讨论】:

    • 在这种方法中,我们无法在 NET 标准库中实现内存缓存行为。请问如何将 IMemorycache 集成到 NET Standard 库中?
    • @Parthi 请阅读此主题:github.com/aspnet/AspNetCore.Docs/issues/7556
    • @mattinsalto 如何设置内存缓存名称?
    【解决方案2】:

    我的回答集中在“在 .Net 核心中我找不到 System.Runtime.Cache”,因为我遇到了同样的问题。对于在特定 OP 的场景中使用 IMemoryCache,接受的答案很棒。


    有两种完全不同的缓存实现/解决方案:

    1 - System.Runtime.Caching/MemoryCache
    2 - Microsoft.Extensions.Caching.Memory/IMemoryCache


    System.Runtime.Caching/MemoryCache:
    这与过去的 ASP.Net MVC 的HttpRuntime.Cache 几乎相同。 您可以在 ASP.Net CORE 上使用它而无需任何依赖注入。使用方法如下:

    // First install 'System.Runtime.Caching' (NuGet package)
    
    // Add a using
    using System.Runtime.Caching;
    
    // To get a value
    var myString = MemoryCache.Default["itemCacheKey"];
    
    // To store a value
    MemoryCache.Default["itemCacheKey"] = myString;
    

    Microsoft.Extensions.Caching.Memory
    这与依赖注入紧密耦合。这是实现它的一种方法:

    // In asp.net core's Startup add this:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
    }
    

    在控制器上使用它:

    // Add a using
    using Microsoft.Extensions.Caching.Memory;
    
    // In your controller's constructor, you add the dependency on the 'IMemoryCache'
    public class HomeController : Controller
    {
        private IMemoryCache _cache;
        public HomeController(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }
    
        public void Test()
        {
            // To get a value
            string myString = null;
            if (_cache.TryGetValue("itemCacheKey", out myString))
            { /*  key/value found  -  myString has the key cache's value*/  }
    
    
            // To store a value
            _cache.Set("itemCacheKey", myString);
        }
    }
    

    正如@WillC 所指出的,这个答案实际上是Cache in-memory in ASP.NET Core 文档的摘要。您可以在那里找到更多信息。

    【讨论】:

    • 感谢您的信息。我正在将一些代码从 .net 移植到核心,这很有用,因为两个重叠的实现令人困惑。
    • 我还发现了这个链接来扩展你在这里所说的内容。 docs.microsoft.com/en-us/aspnet/core/performance/caching/…
    • @WillC 我很高兴这个答案对您有所帮助!是的,您提供的链接实际上是我执行这些实现的来源。我的回答有点像您提供的文档中的“摘要”。我认为这是不必要的,但由于它与您相关,所以我会将其包含在我的答案中。
    • @LeiYang 好问题。这取决于一些因素:如果您已经在使用依赖注入,您可以轻松地与其他依赖项一起实现 Microsoft.Extensions.Caching.Memory/IMemoryCache。此外,如果您使用的是 ASP.Net Core,那么使用 DI 是一种最佳实践。另一方面,如果您的使用是特定的、简单的和有限的,我认为使用System.Runtime.Caching/MemoryCache 没有任何设计问题。而且,后者对于原型设计非常有帮助。
    • @LeiYang 恢复它是一个设计方面。我会说在质疑“我什么时候应该使用依赖注入”时,答案是一样的。我还应该提到,新的Microsoft.Extensions.Caching.Memory/IMemoryCache 是System.Runtime.Caching/MemoryCache 的“更新”和当前版本,目前仅作为遗留解决方案支持。所以IMemoryCache 的性能更好,但实际上绝大多数情况下性能差异绝对可以忽略不计。
    【解决方案3】:
    • 通过构造函数注入 MemoryCache(从 nugget 获取引用 Microsoft.Extensions.Caching.Memory)
     private readonly IMemoryCache memoryCache;
    
    • 代码实现
     private IList<Employee> GetListFromCache()
            {
                const string Key = "employee";
                IList<Employee> cacheValue = null;
                if (!this.memoryCache.TryGetValue(Key, out cacheValue))
                {
                    //// Key not in cache, so get data.
                    cacheValue = this.context.Employee.AsNoTracking().Include(x => 
                    x.Id).ToList();
                           
                    //// Set cache options.
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        //// Keep in cache for this time, reset time if accessed.
                        .SetSlidingExpiration(TimeSpan.FromDays(1));
    
                    //// Save data in cache.
                    this.memoryCache.Set(Key, cacheValue, cacheEntryOptions);
                }
    
                return cacheValue;
            }
    
    

    在 Startup.cs 的 ConfigureServices 下注册 AddMemoryCache

     services.AddMemoryCache();
    
    • 模拟 IMemoryCache 用于单元测试
         /// <summary>Gets the memory cache.</summary>
            /// <returns> Memory cache object.</returns>
            public IMemoryCache GetMemoryCache()
            {
                var services = new ServiceCollection();
                services.AddMemoryCache();
                var serviceProvider = services.BuildServiceProvider();
    
                return serviceProvider.GetService<IMemoryCache>();
            }
    
    //Inject memory cache in constructor for unit test
      this.memoryCache = text.GetMemoryCache();
    

    【讨论】:

      【解决方案4】:

      如果您使用 Asp.net 核心,则无需为缓存自定义 SingleTon,因为您的缓存类支持 Asp.net 核心。

      要使用 IMemoryCache 将数据设置到服务器的内存中,您可以执行以下操作:

      public void Add<T>(T o, string key)
      {
          if (IsEnableCache)
          {
              T cacheEntry;
      
              // Look for cache key.
              if (!_cache.TryGetValue(key, out cacheEntry))
              {
                  // Key not in cache, so get data.
                  cacheEntry = o;
      
                  // Set cache options.
                  var cacheEntryOptions = new MemoryCacheEntryOptions()
                      // Keep in cache for this time, reset time if accessed.
                      .SetSlidingExpiration(TimeSpan.FromSeconds(7200));
      
                  // Save data in cache.
                  _cache.Set(key, cacheEntry, cacheEntryOptions);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-12
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-20
        • 1970-01-01
        • 1970-01-01
        • 2017-10-17
        相关资源
        最近更新 更多