系列导航
Q87. 什么是 caching(缓存)以及什么时候使用缓存?
Ans. Caching 是高性能 web 应用程序的一个很重要的方面。Caching 是一种提高 web 应用程序性能的高效方法。Caching 提供了存储经常访问的数据以及重用这些数据的一种方式。
何时使用缓存:
方法去缓存基于自定义的请求类型(比如 cookie,role,theme,browser 等等)的多个版本的内容;
- VaryByCustom
Q88. 缓存的好处是什么?
Ans. 主要有以下几点:
Q89. 什么是 output caching(输出缓存)?
Ans.
过滤器允许你缓存一个 action 的输出数据。默认该过滤器只缓存 60s。60s 后,ASP.NET MVC 会重新执行 action 并再次缓存输出。
- OutputCache
- class HomeController : Controller
- {
- [OutputCache(Duration = 20, VaryByParam = "none")]
- public ActionResult Index()
- {
- ViewBag.Message = DateTime.Now.ToString();
- return View();
- }
- }
action 的输出将会被缓存 20s。
- Index()
Output Caching Location(输出缓存的路径)
默认内容被缓存在 3 个地方:web server(web 服务器),proxy server(代理服务器),user's browser(用户浏览器)。
你可以通过修改
特性的
- OutputCache
参数来控制内容缓存的地方。
- Location
可以设置为:
- Location
,
- Any
,
- Client
,
- Downstream
,
- Server
,
- None
。 默认,
- ServerAndClient
参数设置为
- Location
可以适用于大部分场景。但是有些时候你可能需要对缓存数据有更多的控制。
- Any
Q90. ASP.NET MVC 中什么是 Donut caching 和 Donut hole caching?
Ans. Donut caching 缓存除了部分内容以外的整个页面。在介绍 Donut caching 之前,我们使用 Output Caching(输出缓存)来缓存整个页面。
何时使用 Donut caching?
假设你有一个 web 应用程序中有一些页面,比如主页,主页展示的内容对所有用户来说都是一样的除了用户的登陆信息比如用户名。如果你想通过
来为所有用户缓存主页,那么整个页面将会为每个用户分别缓存。这将不是一个好的实践,因为如果同时又 1000 个登陆的用户,就将会缓存 1000 个网页。
- OutputCache(VaryByParam=UserID)
为了解决这个问题,Donut Caching 被引入,它为所有用户缓存一份整个页面除了部分动态内容。这个动态部分实际上类似于缓存内容上的一个洞(像甜甜圈)。
Donut caching 非常适用于对大部分内容很少改变但又有部分内容动态改变的页面进行缓存。
Donut Hole caching
Donut Hole Caching 和 Donut Caching 刚好相反,它用来缓存页面中的一小部分。
何时使用 Donut Hole caching?
假设你有一个 web 应用程序,它需要在每个页面里显示产品列表,那么这时以 html 的形式缓存一个产品列表就是很需要的了,Donut Hole Caching 就是设计来处理这种情况。
ASP.NET MVC 通知在 Child Action 上使用 OutputCache 来支持 Donut Hole caching:
- class HomeController : Controller
- {
- [ChildActionOnly]
- [OutputCache(Duration = 60)]
- public ActionResult CategoriesList()
- {
- // Get categories list from the database and
- // pass it to the child view
- ViewBag.Categories = GetCategories();
- return View();
- }
- }
来源: http://www.cnblogs.com/sheng-jie/p/6482799.html