如何在MVC 4应用程序中的内存中缓存数据 [英] How to cache data in memory in a mvc 4 application

查看:92
本文介绍了如何在MVC 4应用程序中的内存中缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的mvc 4应用程序中实现缓存.我想一次检索数据,而不必 来回回数据库.我跟随下面的网址.我的代码运行良好,但没有发生缓存

I am trying to implement caching in my mvc 4 application. I want to retrieve data once and not have to go back to the database back and forth. I followed the url below. My code runs well but caching is not happening

http://stevescodingblog.co.uk/net4-caching-with-mvc/

如果我在下面的方法上设置了一个断点,它将永远不会从缓存中返回数据.总是要获取新数据 即vehicleData始终为空.

If i set a break point on the method below it never returns data from the cache. It is always going to get new data i.e vehicleData is always null.

我是新手.实施内存缓存的最佳方法是什么?我正在使用MVC 4和Visual Studio2013.Cache.set是否已过时?

I am new to caching. What is the best way to implement memory caching? I am using mvc 4 and visual studio 2013. Is it that Cache.set is outdated?

      public IEnumerable<Vehicle> GetVehicles()
            {
                // First, check the cache
                IEnumerable<Vehicle> vehicleData = Cache.Get("vehicles") as IEnumerable<Vehicle>;

                // If it's not in the cache, we need to read it from the repository
                if (vehicleData == null)
                {
                    // Get the repository data
                    //vehicleData = DataContext.Vehicles.OrderBy(v =&gt; v.Name).ToList();

                    vehicleData = DataContext.Vehicles.OrderBy(g=>g.Name).ToList();

                    if (vehicleData != null)
                    {
                        // Put this data into the cache for 30 minutes
                        Cache.Set("vehicles", vehicleData, 30);

                    }
                }

                return vehicleData;
            }

推荐答案

引用模型中的System.Web dll并使用System.Web.Caching.Cache

Reference the System.Web dll in your model and use System.Web.Caching.Cache

public string[] GetNames()
{
  string[] names = null;
  if(Cache["names"] == null)
  {
    names = DB.GetNames();
    Cache["names"] = names;
  }
  else
  {
    names = Cache["names"];
  }
  return names;
}

http://www.dotnet-tricks.com/Tutorial/mvc/4R5c050113-Understanding-Caching-in-Asp.Net-MVC-with-example.html

http://www.codeproject. com/Articles/757201/A-Beginners-Tutorial-forUnderstanding-and-Imple

这篇关于如何在MVC 4应用程序中的内存中缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆