我已经阅读了大量关于MVC应用程序中的页面缓存和部分页面缓存的信息。然而,我想知道你将如何缓存数据。

在我的场景中,我将使用LINQ到实体(实体框架)。在第一次调用GetNames(或任何方法)时,我想从数据库中获取数据。我想将结果保存在缓存中,并在第二次调用时使用缓存版本(如果存在)。

谁能举例说明这将如何工作,这应该在哪里实现(模型?),如果它将工作。

我在传统的ASP中见过这种情况。NET应用程序,通常用于非常静态的数据。


当前回答

AppFabric缓存是一种分布式的内存缓存技术,可以跨多个服务器使用物理内存以键值对的形式存储数据。AppFabric为. net Framework应用程序提供了性能和可伸缩性改进。概念和架构

其他回答

我要说的是,如果您发现以前的解决方案非常复杂,那么在这个持久化数据问题上实现Singleton可以是一个解决方案

 public class GPDataDictionary
{
    private Dictionary<string, object> configDictionary = new Dictionary<string, object>();

    /// <summary>
    /// Configuration values dictionary
    /// </summary>
    public Dictionary<string, object> ConfigDictionary
    {
        get { return configDictionary; }
    }

    private static GPDataDictionary instance;
    public static GPDataDictionary Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GPDataDictionary();
            }
            return instance;
        }
    }

    // private constructor
    private GPDataDictionary() { }

}  // singleton
HttpContext.Current.Cache.Insert("subjectlist", subjectlist);

我使用两个类。第一个是缓存核心对象:

public class Cacher<TValue>
    where TValue : class
{
    #region Properties
    private Func<TValue> _init;
    public string Key { get; private set; }
    public TValue Value
    {
        get
        {
            var item = HttpRuntime.Cache.Get(Key) as TValue;
            if (item == null)
            {
                item = _init();
                HttpContext.Current.Cache.Insert(Key, item);
            }
            return item;
        }
    }
    #endregion

    #region Constructor
    public Cacher(string key, Func<TValue> init)
    {
        Key = key;
        _init = init;
    }
    #endregion

    #region Methods
    public void Refresh()
    {
        HttpRuntime.Cache.Remove(Key);
    }
    #endregion
}

第二个是缓存对象列表:

public static class Caches
{
    static Caches()
    {
        Languages = new Cacher<IEnumerable<Language>>("Languages", () =>
                                                          {
                                                              using (var context = new WordsContext())
                                                              {
                                                                  return context.Languages.ToList();
                                                              }
                                                          });
    }
    public static Cacher<IEnumerable<Language>> Languages { get; private set; }
}

AppFabric缓存是一种分布式的内存缓存技术,可以跨多个服务器使用物理内存以键值对的形式存储数据。AppFabric为. net Framework应用程序提供了性能和可伸缩性改进。概念和架构

参考系统。并使用System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

有点简化了,但我想应该可以。这不是MVC特定的,我一直使用这种方法缓存数据。