Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 742
Hamid Reza Avatar asked Feb 21 '13 10:02

Hamid Reza


People also ask

When would you use a cache over a database?

In-memory data caching can be one of the most effective strategies to improve your overall application performance and to reduce your database costs. Caching can be applied to any type of database including relational databases such as Amazon RDS or NoSQL databases such as Amazon DynamoDB, MongoDB and Apache Cassandra.

What is difference between cache and database?

Databases are generally regarded as persistent, consistent and queryable data stores. Caches behave like databases, except they shed many features to improve performance like it favors fast access over durability & consistency.

Can cache be read?

The browser can read data from the browser cache faster than it can reread the files from the webpage. Cache is important for several reasons: The use of cache reduces latency for active data. This results in higher performance for a system or application.


1 Answers

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

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

    }
like image 164
cuongle Avatar answered Oct 15 '22 23:10

cuongle