MVC3缓存之一:使用页面缓存

MVC3缓存之一:使用页面缓存

在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可。

我们建一个Demo来测试一下,在此Demo中,在View的Home目录下的Index.cshtml中让页面输入当前的时间。

[csharp] view plain copy

  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <title>Index</title>
  8. </head>
  9. <body>
  10. <div>
  11. <h2>
  12. 现在时间:@DateTime.Now.ToString("T")</h2>
  13. </div>
  14. </body>
  15. </html>

在Controllers中添加对应的Action,并加上OutputCache属性。

[csharp] view plain copy

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = 5, VaryByParam = "none")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

刷新页面即可看到页面做了一个5秒的缓存。当页面中数据不是需要实时的呈现给用户时,这样的页面缓存可以减小实时地对数据处理和请求,当然这是针对整个页面做的缓存,缓存的粒度还是比较粗的。

缓存的位置

可以通过设置缓存的Location属性,决定将缓存放置在何处。

Location可以设置的属性如下:

· Any

· Client

· Downstream

· Server

· None

· ServerAndClient

Location的默认值为Any。一般推荐将用户侧的信息存储在Client端,一些公用的信息存储在Server端。

加上Location应该像这样。

[csharp] view plain copy

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = 5, VaryByParam = "none", Location = OutputCacheLocation.Client, NoStore = true)]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

缓存依赖

VaryByParam可以对缓存设置缓存依赖条件,如一个产品详细页面,可能就是根据产品ID进行缓存页面。

缓存依赖应该设置成下面这样。

在MVC3中对输出缓存进行了改进,OutputCache不需要手动指定VaryByParam,会自动使用Action的参数作为缓存过期条件。

[csharp] view plain copy

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

另一种通用的设置方法

当我们需要对多个Action进行统一的设置时,可以在web.config文件中统一配置后进行应用即可。

在web.config中配置下Caching节点

[csharp] view plain copy

  1. <caching>
  2. <outputCacheSettings>
  3. <outputCacheProfiles>
  4. <add name="Cache1Hour" duration="3600" varyByParam="none"/>
  5. </outputCacheProfiles>
  6. </outputCacheSettings>
  7. </caching>

那么在Action上使用该配置节点即可,这样的方法对于统一管理配置信息比较方便。

[csharp] view plain copy

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(CacheProfile = "Cache1Hour")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

MVC3缓存之二:页面缓存中的局部动态

MVC中有一个Post-cache substitution的东西,可以对缓存的内容进行替换。

使用Post-Cache Substitution

  • 定义一个返回需要显示的动态内容string的方法。
  • 调用HttpResponse.WriteSubstitution()方法即可。

示例,我们在Model层中定义一个随机返回新闻的方法。

[csharp] view plain copy

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. namespace MvcApplication1.Models
  5. {
  6. public class News
  7. {
  8. public static string RenderNews(HttpContext context)
  9. {
  10. var news = new List<string>
  11. {
  12. "Gas prices go up!",
  13. "Life discovered on Mars!",
  14. "Moon disappears!"
  15. };
  16. var rnd = new Random();
  17. return news[rnd.Next(news.Count)];
  18. }
  19. }
  20. }

然后在页面中需要动态显示内容的地方调用。

[csharp] view plain copy

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
  2. <%@ Import Namespace="MvcApplication1.Models" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" >
  5. <head runat="server">
  6. <title>Index</title>
  7. </head>
  8. <body>
  9. <div>
  10. <% Response.WriteSubstitution(News.RenderNews); %>
  11. <hr />
  12. The content of this page is output cached.
  13. <%= DateTime.Now %>
  14. </div>
  15. </body>
  16. </html>

如在上面文章中说明的那样,给Controller加上缓存属性。

[csharp] view plain copy

  1. using System.Web.Mvc;
  2. namespace MvcApplication1.Controllers
  3. {
  4. [HandleError]
  5. public class HomeController : Controller
  6. {
  7. [OutputCache(Duration=60, VaryByParam="none")]
  8. public ActionResult Index()
  9. {
  10. return View();
  11. }
  12. }
  13. }

可以发现,程序对整个页面进行了缓存60s的处理,但调用WriteSubstitution方法的地方还是进行了随机动态显示内容。

对Post-Cache Substitution的封装

将静态显示广告Banner的方法封装在AdHelper中。

[csharp] view plain copy

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.Web.Mvc;
  5. namespace MvcApplication1.Helpers
  6. {
  7. public static class AdHelper
  8. {
  9. public static void RenderBanner(this HtmlHelper helper)
  10. {
  11. var context = helper.ViewContext.HttpContext;
  12. context.Response.WriteSubstitution(RenderBannerInternal);
  13. }
  14. private static string RenderBannerInternal(HttpContext context)
  15. {
  16. var ads = new List<string>
  17. {
  18. "/ads/banner1.gif",
  19. "/ads/banner2.gif",
  20. "/ads/banner3.gif"
  21. };
  22. var rnd = new Random();
  23. var ad = ads[rnd.Next(ads.Count)];
  24. return String.Format("<img src=‘{0}‘ />", ad);
  25. }
  26. }
  27. }

这样在页面中只要进行这样的调用,记得需要在头部导入命名空间。

[csharp] view plain copy

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
  2. <%@ Import Namespace="MvcApplication1.Models" %>
  3. <%@ Import Namespace="MvcApplication1.Helpers" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml" >
  6. <head runat="server">
  7. <title>Index</title>
  8. </head>
  9. <body>
  10. <div>
  11. <% Response.WriteSubstitution(News.RenderNews); %>
  12. <hr />
  13. <% Html.RenderBanner(); %>
  14. <hr />
  15. The content of this page is output cached.
  16. <%= DateTime.Now %>
  17. </div>
  18. </body>
  19. </html>

使用这样的方法可以使得内部逻辑对外呈现出更好的封装。

MVC3缓存之三:MVC3中的局部缓存(Partial Page)

MVC3
版本中,新增了一个叫做Partial
Page的东西,即可以对载入到当前页面的另外的一个View进行缓存后输出,这与我们之前讨论的局部动态刚好相反了,即之前我们进行这个页面的缓存,然
后对局部进行动态输出,现在的解决方案是:页面时动态输出的,而对需要缓存的局部进行缓存处理。查来查去还没有看到局部动态的解决方案,所以我们先看看局
部缓存的处理方法。

局部缓存(Partial Page)

我们先建立一个需要局部缓存的页面View,叫做PartialCache.cshtml,页面内容如下:

[csharp] view plain copy

  1. <p>@ViewBag.Time2</p>

在其对应的Controller中添加对应的Action

[csharp] view plain copy

  1. [OutputCache(Duration = 10)]
  2. public ActionResult PartialCache()
  3. {
  4. ViewBag.Time2 = DateTime.Now.ToLongTimeString();
  5. return PartialView();
  6. }

我们可以看到对其Action做了缓存处理,对页面进行缓存10秒钟。

而在Index的View中调用此缓存了的页面则需要这样:

[csharp] view plain copy

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>
  5. OutputCache Demo</h2>
  6. <p>
  7. No Cache</p>
  8. <div>@DateTime.Now.ToLongTimeString()
  9. </div>
  10. <br />
  11. <p>
  12. Partial Cache 10 mins
  13. </p>
  14. <div class="bar2">@Html.Action("PartialCache", "Index", null)</div>

运行后,我们刷新页面可以发现Index的主体没有缓存,而引用到的PartialCache进行了10秒缓存的处理。

时间: 2024-07-29 06:46:58

MVC3缓存之一:使用页面缓存的相关文章

如何设置页面缓存或不用页面缓存

一.设置页面缓存 1.直接在页面上用<%@ OutputCache Duration="10" VaryByParam="None" %>声明来缓存页面 2.使用服务端方法: //将Cache-Control标头设置为HttpCacheAbility值 Response.Cache.SetCacheability(HttpCacheability.Public); //将页面的绝对过期时间 Response.Cache.SetExpires(DateTi

Yii的缓存机制之页面缓存

页面缓存是不能通过片段缓存来实现的,因为布局和内容不能同时缓存.只能通过过滤器来生成缓存. 实现方法: 在控制器里使用过滤器来实现 function filters (){ return array( array( 'system.web.widgets.COutputCache + detail', //只针对detail有效 'duration' => 3600, //缓存时间 'varyByParam' => array('id'), //缓存依赖(通过不同的id实现不同的缓存) ),

MVC3缓存:使用页面缓存

在以前的WebForm的开发中,在页面的头部加上OutputCache即可启用页面缓存,而在MVC3中,使用了Razor模板引擎的话,该如何使用页面缓存呢?如何启用另一个参考的博客地址:http://www.cnblogs.com/luminji/archive/2011/09/14/2174751.html在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可. 我们建一个Demo来测试一下,在此Demo中,在View的Home目录下的Index.

探索ASP.NET MVC5系列之~~~5.缓存篇(页面缓存+二级缓存)

其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.html#mvc 本章Demo:https://github.com/dunitian/LoTCodeBase/blob/master/NetCode/6.网页基础/BMVC5/MVC5Base/Controllers/CacheController.cs 这次来篇放松的,咱们不要老是说安全相关的东西.

缓存插件 EHCache 页面缓存CachingFilter

Ehcache基本用法 CacheManager cacheManager = CacheManager.create(); // 或者 cacheManager = CacheManager.getInstance(); // 或者 cacheManager = CacheManager.create("/config/ehcache.xml"); // 或者 cacheManager = CacheManager.create("http://localhost:8080

Drupal是如何避免页面缓存保存Message信息的

函数page_get_cache代码: function page_get_cache($status_only = FALSE) { static $status = FALSE; global $user, $base_root; if ($status_only) { return $status; } $cache = NULL; if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(d

MVC3缓存(一):页面缓存

启用页面缓存 在MVC3中如果要启用页面缓存,需要在页面对应的Action前面加上一个OutputCache属性. @{ ViewBag.Title = "主页"; } <!DOCTYPE html> <html> <head> <title>页面缓存</title> </head> <body> 现在时间:@DateTime.Now.ToString("T") </body&

[转]MVC3缓存之一:使用页面缓存

本文转自:http://www.cnblogs.com/parry/archive/2011/03/19/OutputCache_In_MVC3.html 在以前的WebForm的开发中,在页面的头部加上OutputCache即可启用页面缓存,而在MVC3中,使用了Razor模板引擎的话,该如何使用页面缓存呢? 如何启用 在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可. 我们建一个Demo来测试一下,在此Demo中,在View的Home目录下

Haproxy + Varnish 实现WEB静态页面缓存

一.缓存介绍及Haproxy+Varnish架构图: 1.)简介:现阶段的互联网时代,缓存成为一个必不可少的一环,不论是对于整体架构的优化,减少服务器的压力,加速用户访问速度,都是需要用到缓存.而缓存的种类也是很多,例如CDN,Squid,Memcached,Varnish,已经成为一个中型,大型架构中基本的实现. 2.)CDN缓存技术是根据全国各地的用户,直接缓存到离用户最近的地方. 3.)Squid是处于前端的缓存,并且可以用作为正向代理,反向代理,透明代理. 4.)Memcached主要用