How to cache data in a MVC application

后端 未结 14 1126
鱼传尺愫
鱼传尺愫 2020-11-22 11:39

I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

In my scena

14条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 12:29

    Here's a nice and simple cache helper class/service I use:

    using System.Runtime.Caching;  
    
    public class InMemoryCache: ICacheService
    {
        public T GetOrSet(string cacheKey, Func getItemCallback) where T : class
        {
            T item = MemoryCache.Default.Get(cacheKey) as T;
            if (item == null)
            {
                item = getItemCallback();
                MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
            }
            return item;
        }
    }
    
    interface ICacheService
    {
        T GetOrSet(string cacheKey, Func getItemCallback) where T : class;
    }
    

    Usage:

    cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));
    

    Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

    Example:

    var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())
    

提交回复
热议问题