C# 如果存在而不是数据库,如何缓存对象并从内存中读取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14999599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:43:43  来源:igfitidea点击:

How can I cache objects and read from memory if it exists instead of database?

c#cachinginterface

提问by Hamid Reza

I have four classes as following:

我有四个类如下:

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();
    }
}

And in my controller, I have

在我的控制器中,我有

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

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

Now, I want to do cache sections on memory for a specific time in order to read sections from cache if it exists, else read it from database.

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

采纳答案by cuongle

Simple possible approach, you can use MemoryCache, the code will look like:

简单可行的方法,您可以使用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);

    }

回答by Tomtom

You do the caching by adding a new class with a timeout. When you read the first time, you read directly from the database and write the data into a property of the new class and make a timestamp. In the next read operation, you check your new class to see if the timeout has been reached. If not, you read the data from the new class. Otherwise, you read from the database and put it into the cache class and update the timeout.

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

回答by Jamie Pearcey

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);
    }
}