【问题标题】:How can I cache objects and read from memory if it exists instead of database?如果它存在而不是数据库,我如何缓存对象并从内存中读取?
【发布时间】:2013-02-06 14:52:43
【问题描述】:

我有以下四个课程:

public class Section
{
    public int SectionId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string MetaTag { get; set; }
    public string MetaDescription { get; set; }
    public string UrlSafe { get; set; }
    public string Header { get; set; }
    public string ImageName { get; set; }
}       

public interface ISectionRepository
{
    List<Section> GetAllSections();
}

public class SectionRepository : ISectionRepository
{
    Context context = new Context();

    public List<Section> GetAllSections()
    {
        return context.Sections.ToList();
    }
}

public class SectionApplication
{
    SectionRepository sectionRepo = new SectionRepository();

    public List<Section> GetAllSections()
    {
        return sectionRepo.GetAllSections();
    }
}

在我的控制器中,我有

public class SectionController : Controller
{
    SectionApplication sectionApp = new SectionApplication();

    public ActionResult Index()
    {
        return View(sectionApp.GetAllSections());
    }
}

现在,我想在内存中缓存部分特定时间,以便从缓存中读取部分(如果存在),否则从数据库中读取。

【问题讨论】:

标签: c# caching interface


【解决方案1】:

简单可行的方法,你可以使用MemoryCache,代码如下:

public List<Section> GetAllSections()
    {
        var memoryCache = MemoryCache.Default;

        if (!memoryCache.Contains("section"))
        {
            var expiration = DateTimeOffset.UtcNow.AddMinutes(5);
            var sections = context.Sections.ToList();

            memoryCache.Add("section", section, expiration);
        }

        return memoryCache.Get("section", null);

    }

【讨论】:

  • 我有一个错误:无法将类型'object'隐式转换为 System.Collections.Generic.List'。存在显式转换(您是否缺少演员表?)我该怎么办?
  • @HamidReza:从缓存中取出对象时应该显式转换
  • OW。是的。我做到了。谢谢。
  • 对于这个例子,看起来AddOrGetExisting也可以代替。
【解决方案2】:

您通过添加一个带有超时的新类来进行缓存。第一次读取时,直接从数据库中读取数据并将数据写入新类的属性并制作时间戳。在下一个读取操作中,您检查新类以查看是否已达到超时。如果没有,则从新类中读取数据。否则,您从数据库中读取并将其放入缓存类并更新超时。

【讨论】:

    【解决方案3】:
    public interface IRepositoryCollection
    {
        DateTime dateCreated { get; set; }
    }
    
    public class Cache<T> : Dictionary<string, T>
    {
        private int cacheDuration = 1;
        private int maxCacheSize = 20;
    
        public Cache(int cacheDuration, int maxCacheSize)
        {
            this.cacheDuration = cacheDuration;
            this.maxCacheSize = maxCacheSize;
        }
    
        public new void Add(string key, T invoices)
        {
            base.Add(key, invoices);
            RemoveOld();
            RemoveOldest();
        }
    
        public void RemoveOld()
        {
            foreach (KeyValuePair<string, T> cacheItem in this)
            {
                Interfaces.IRepositoryCollection currentvalue = (Interfaces.IRepositoryCollection)cacheItem.Value;
    
                if (currentvalue.dateCreated < DateTime.Now.AddHours(-cacheDuration))
                {
                    this.Remove(cacheItem.Key);
                }
            }
        }
    
        public void RemoveOldest()
        {
            do
            {
                this.Remove(this.First().Key);
            }
            while (this.Count > maxCacheSize);
        }
    }
    
    
    public class ProformaInvoiceCache
    {
        private static Cache<ProformaInvoices> cache = new Cache<ProformaInvoices>(1, 20);
    
        public static string AddInvoiceCollection(ProformaInvoices invoices)
        {
            // Adds invoice collection to static instance of cache, returns guid required to retrieve item from cache
            return cache.Add(invoices);
        }
    
        public static ProformaInvoices GetInvoiceCollection(string guid)
        {
            // Gets invoice collection from cache corresponding to passed guid
            return cache.Get(guid);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多