How to cache data in a MVC application

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

    Here's an improvement to Hrvoje Hudo's answer. This implementation has a couple of key improvements:

    • Cache keys are created automatically based on the function to update data and the object passed in that specifies dependencies
    • Pass in time span for any cache duration
    • Uses a lock for thread safety

    Note that this has a dependency on Newtonsoft.Json to serialize the dependsOn object, but that can be easily swapped out for any other serialization method.

    ICache.cs

    public interface ICache
    {
        T GetOrSet(Func getItemCallback, object dependsOn, TimeSpan duration) where T : class;
    }
    

    InMemoryCache.cs

    using System;
    using System.Reflection;
    using System.Runtime.Caching;
    using Newtonsoft.Json;
    
    public class InMemoryCache : ICache
    {
        private static readonly object CacheLockObject = new object();
    
        public T GetOrSet(Func getItemCallback, object dependsOn, TimeSpan duration) where T : class
        {
            string cacheKey = GetCacheKey(getItemCallback, dependsOn);
            T item = MemoryCache.Default.Get(cacheKey) as T;
            if (item == null)
            {
                lock (CacheLockObject)
                {
                    item = getItemCallback();
                    MemoryCache.Default.Add(cacheKey, item, DateTime.Now.Add(duration));
                }
            }
            return item;
        }
    
        private string GetCacheKey(Func itemCallback, object dependsOn) where T: class
        {
            var serializedDependants = JsonConvert.SerializeObject(dependsOn);
            var methodType = itemCallback.GetType();
            return methodType.FullName + serializedDependants;
        }
    }
    

    Usage:

    var order = _cache.GetOrSet(
        () => _session.Set().SingleOrDefault(o => o.Id == orderId)
        , new { id = orderId }
        , new TimeSpan(0, 10, 0)
    );
    

提交回复
热议问题