C# 如何在MVC内核中使用缓存管理器?

C# 如何在MVC内核中使用缓存管理器?,c#,asp.net,model-view-controller,core,C#,Asp.net,Model View Controller,Core,我需要激活二级缓存EF Core,以便在下次缓存查询结果,而不是缓存数据库。取决于您的项目。您可以通过多种方式缓存数据: 在存储库模式中实现缓存 在单独的类中编写自己的缓存管理器 使用类似Redis的系统进行缓存 ASP.NET核心中的响应缓存: 这是我的CacheManager类 public class CacheManagerAdapter : ICacheService { private readonly YYYApi _api; privat

我需要激活二级缓存EF Core,以便在下次缓存查询结果,而不是缓存数据库。

取决于您的项目。您可以通过多种方式缓存数据:

  • 在存储库模式中实现缓存
  • 在单独的类中编写自己的缓存管理器
  • 使用类似Redis的系统进行缓存
  • ASP.NET核心中的响应缓存:

    • 这是我的CacheManager类

      public class CacheManagerAdapter : ICacheService
          {
              private readonly YYYApi _api;
              private ICacheManager<object> _cacheManager;
              private static readonly string _cacheName;
      
              static CacheManagerAdapter()
              {
                  _cacheName = ConfigurationManager.AppSettings["cacheName"] ?? "CancelBookingCache";
              }
      
              public CacheManagerAdapter(IOptions<YYYApi> options)
              {
                  _api = options.Value;
      
                  _cacheManager = CacheFactory.Build("cacheName", settings => settings
                      .WithUpdateMode(CacheUpdateMode.Up)
                      .WithRedisCacheHandle("redisCache")
                      .And.WithRedisConfiguration("redisCache", _api.cacheHost)
                      .WithJsonSerializer()
                      );
              }
      
              public void Clear()
              {
                  _cacheManager.ClearRegion(_cacheName);
              }
      
              public bool Contains(string key)
              {
                  return _cacheManager.GetCacheItem(key, _cacheName) == null;
              }
      
              public object Get(string key)
              {
                  try
                  {
                      return _cacheManager.GetCacheItem(key, _cacheName).Value;
                  }
                  catch (Exception)
                  {
                      return null;
                  }
      
              }
      
              public T Get<T>(string key, Func<T> getItemCallback) where T : class
              {
                  return _cacheManager.Get<T>(key, _cacheName);
              }
      
              public void Invalidate(Regex pattern)
              {
      
                  throw new NotImplementedException();
              }
      
              public void Invalidate(string key)
              {
                  _cacheManager.Remove(key, _cacheName);
              }
      
              public bool IsSet(string key)
              {
                  throw new NotImplementedException();
              }
      
              public void Set(string key, object data, int cacheTime)
              {
                  try
                  {
                      _cacheManager.AddOrUpdate(key, _cacheName, data, x => data);
                      if (cacheTime > 0)
                      {
                          _cacheManager.Expire(key, _cacheName, ExpirationMode.Absolute, new TimeSpan(0, cacheTime, 0));
                      }
                  }
                  catch (Exception ex)
                  {
      
                  }
              }
          }
      
      公共类cachemanageradepter:ICacheService
      {
      专用只读YYYApi_api;
      私人ICacheManager(缓存管理器);
      私有静态只读字符串_cacheName;
      静态CacheManagerAdapter()
      {
      _cacheName=ConfigurationManager.AppSettings[“cacheName”]??“CancelBookingCache”;
      }
      公共CacheManagerAdapter(IOOptions选项)
      {
      _api=选项。值;
      _cacheManager=CacheFactory.Build(“cacheName”,settings=>settings
      .WithUpdateMode(CacheUpdateMode.Up)
      .WithRedisCacheHandle(“redisCache”)
      .和.WithRedisConfiguration(“redisCache”,_api.cacheHost)
      .WithJsonSerializer()
      );
      }
      公共空间清除()
      {
      _cacheManager.ClearRegion(_cacheName);
      }
      公共bool包含(字符串键)
      {
      return _cacheManager.GetCacheItem(key,_cacheName)==null;
      }
      公共对象获取(字符串键)
      {
      尝试
      {
      返回_cacheManager.GetCacheItem(键,_cacheName).Value;
      }
      捕获(例外)
      {
      返回null;
      }
      }
      公共T Get(字符串键,Func getItemCallback),其中T:class
      {
      返回_cacheManager.Get(键,_cacheName);
      }
      公共无效失效(正则表达式模式)
      {
      抛出新的NotImplementedException();
      }
      公共无效无效(字符串键)
      {
      _cacheManager.Remove(键,\u cacheName);
      }
      公共布尔IsSet(字符串键)
      {
      抛出新的NotImplementedException();
      }
      公共无效集(字符串键、对象数据、int cacheTime)
      {
      尝试
      {
      _AddOrUpdate(key,_cacheName,data,x=>data);
      如果(缓存时间>0)
      {
      _cacheManager.Expire(key,_cacheName,ExpirationMode.Absolute,new TimeSpan(0,cacheTime,0));
      }
      }
      捕获(例外情况除外)
      {
      }
      }
      }
      
      接口

      public interface ICacheService
      {
          void Clear();
          bool Contains(string key);
          T Get<T>(string key, Func<T> getItemCallback) where T : class;
          object Get(string key);
          void Invalidate(string key);
          void Invalidate(Regex pattern);
          bool IsSet(string key);
          void Set(string key, object data, int cacheTime);
      }
      
      公共接口服务
      {
      无效清除();
      bool包含(字符串键);
      T Get(字符串键,Func getItemCallback),其中T:class;
      对象获取(字符串键);
      无效无效(字符串键);
      无效失效(正则表达式模式);
      布尔IsSet(字符串键);
      无效集(字符串键、对象数据、int cacheTime);
      }
      
      这就是启动注入等等

      services.AddSingleton<ICacheService, CacheManagerAdapter>();
      
                  services.AddSingleton<IMMMAdapterService>(new MMMAdapterService(
                      XXX: new XXXController(
                          services.BuildServiceProvider().GetRequiredService<IOptions<YYYApi>>(),
                          _XXXLogger,
                          _diagnosticContext,
                          new CacheManagerAdapter(services.BuildServiceProvider().GetRequiredService<IOptions<YYYApi>>())
                          ), _XXXLogger, _diagnosticContext));
                  services.AddSoapExceptionTransformer((ex) => ex.Message);
      
      services.AddSingleton();
      services.AddSingleton(新的MMMAdapterService(
      XXX:新XXX控制器(
      services.BuildServiceProvider().GetRequiredService(),
      _XXXLogger,
      _诊断上下文,
      新的CacheManagerDatapter(services.BuildServiceProvider().GetRequiredService())
      ),XXXLogger,diagnosticContext);
      services.AddSoapExceptionTransformer((ex)=>ex.Message);
      
      最后,注入控制器

      private readonly YYYApi _api;
      readonly ILogger<XXXController> _logger;
      readonly IDiagnosticContext _diagnosticContext;
      readonly ICacheService _cache;
      
      public XXXController(IOptions<YYYApi> options, ILogger<XXXController> logger, IDiagnosticContext diagnosticContext, ICacheService cache)
          : base(options, logger)
      {
          _api = options.Value;
          _logger = logger;
          _diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
          _cache = cache;
      }
      
      private只读YYYApi\u api;
      只读ILogger\u记录器;
      只读IDiagnosticContext _diagnosticContext;
      只读ICacheService\u缓存;
      公共XXX控制器(IOOptions选项、ILogger记录器、IDiagnosticContext diagnosticContext、ICacheService缓存)
      :基本(选项、记录器)
      {
      _api=选项。值;
      _记录器=记录器;
      _diagnosticContext=diagnosticContext??抛出新的ArgumentNullException(nameof(diagnosticContext));
      _缓存=缓存;
      }
      
      Done,thansk for answer Well如果您对其他功能有任何挑战,请与我的朋友联系写信告诉我我们可以找到答案谢谢您的解决方案@Hamed Nikzad