【问题标题】:What is ASP.NET Micro-Caching?什么是 ASP.NET 微缓存?
【发布时间】:2020-05-16 10:08:04
【问题描述】:

什么是 ASP.NET MVC 微缓存?

一秒缓存的优缺点是什么?

用 C# 在 ASP.NET MVC 项目中实现微缓存的最佳方法是什么?

只需添加[OutputCache(Duration = 1)] 或...?

【问题讨论】:

    标签: c# asp.net asp.net-mvc caching


    【解决方案1】:

    一秒缓存可以避免大量客户端同时请求和执行数据库查询。


    如果不使用缓存,当大量请求同时发送到服务器时,会导致服务器性能下降。

    而且由于缓存时间不长,页面总是会每秒获取新数据。

    短时间缓存兼具两者的优势,它可以同时处理一个大请求,而且每秒获取新的数据。

    但另一方面,短时间缓存无法长时间保存数据。


    而 ASP.NET MVC 提供了客户端/服务器页面缓存属性,只是在上面的操作(或整个控制器)上添加了一个属性。它将缓存所有动作(或控制器)。

    例子:

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            [OutputCache(Duration = 3)]
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    

    此代码将缓存此操作 3 秒,OutputCache 默认LocationAny(缓存客户端和服务器)。

    在客户端缓存:

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            [OutputCache(Duration = 3, Location=OutputCacheLocation.Client)]
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    

    在服务器端缓存:

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            [OutputCache(Duration = 3, Location=OutputCacheLocation.Server)]
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    

    另外,添加VaryByParam属性让缓存可以因参数而异。在同一个动作中,用户使用不同的参数会得到不同的缓存,相同的参数会得到相同的缓存版本。

    这可以用于像产品信息页面这样的缓存。

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            [OutputCache(Duration = 3, VaryByParam = "id")]
            public ActionResult ProductDetail(int id)
            {
                ViewBag.detail = id;
                return View();
            }
        }
    }
    

    OutputCache有很多属性和功能,您可以访问msdn获取更多信息。

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 2012-01-26
      • 1970-01-01
      相关资源
      最近更新 更多