How to cache data in a MVC application

后端 未结 14 1346
鱼传尺愫
鱼传尺愫 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:09

    Extending @Hrvoje Hudo's answer...

    Code:

    using System;
    using System.Runtime.Caching;
    
    public class InMemoryCache : ICacheService
    {
        public TValue Get(string cacheKey, int durationInMinutes, Func getItemCallback) where TValue : class
        {
            TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
            if (item == null)
            {
                item = getItemCallback();
                MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
            }
            return item;
        }
    
        public TValue Get(string cacheKeyFormat, TId id, int durationInMinutes, Func getItemCallback) where TValue : class
        {
            string cacheKey = string.Format(cacheKeyFormat, id);
            TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
            if (item == null)
            {
                item = getItemCallback(id);
                MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
            }
            return item;
        }
    }
    
    interface ICacheService
    {
        TValue Get(string cacheKey, Func getItemCallback) where TValue : class;
        TValue Get(string cacheKeyFormat, TId id, Func getItemCallback) where TValue : class;
    }
    

    Examples

    Single item caching (when each item is cached based on its ID because caching the entire catalog for the item type would be too intensive).

    Product product = cache.Get("product_{0}", productId, 10, productData.getProductById);
    

    Caching all of something

    IEnumerable categories = cache.Get("categories", 20, categoryData.getCategories);
    

    Why TId

    The second helper is especially nice because most data keys are not composite. Additional methods could be added if you use composite keys often. In this way you avoid doing all sorts of string concatenation or string.Formats to get the key to pass to the cache helper. It also makes passing the data access method easier because you don't have to pass the ID into the wrapper method... the whole thing becomes very terse and consistant for the majority of use cases.

提交回复
热议问题