翻译自:http://weblogs.asp.net/scottgu/archive/2010/01/27/extensible-output-caching-with-asp-net-4-vs-2010-and-net-4-0-series.aspx

 

输出缓存的前世今生

   ASP.NET 1.0引入输出缓存的概念,这使得开发者可以缓存页面、控件、控制器以及HTTP响应的输出到内存中。在后续的Web请求,ASP.NET就可以使用缓存中的内容更快响应。

   ASP.NET的输出缓存系统足够灵活,使得我们可以根据不同的查询字符串或者表单post参数来缓存不同版本的内容。例如test.aspx?category=Vegerable 和 test.aspx?category.aspx?category=Meat。它也允许我们根据浏览器类型或者用户语言偏好来缓存不同版本的内容。比如你可以为应用的手机版本缓存一份数据而为桌面版本缓存另外一份。

   我们也可以通过配置ASP.NET来为缓存项设置特定的缓存时间(如1分钟)。我们也可以配置ASP.NET的缓存项根据外部事件动态更新缓存(比如数据库数据更新)。

   但是ASP.NET V1到ASP.NET V3.5都只允许内存缓存。

 

ASP.NET 4输出缓存扩展

   ASP.NET 4扩展了输出缓存使得我们可以配置一个或多个输出缓存provider(output cache providers)。输出缓存provider可以使用任意存储机制来持久化输出缓存内容。这使得我们可以把缓存内容存在本地或者远程磁盘、数据库、云端或者分布式缓存引擎中(如memcached或者velocity)。

   我们可以通过集成ASP.NET中的System.Web.Caching.OutputCacheProvider类来定制自己的输出缓存provider。然后我们重4个公共方法来实现添加/移除/检索/更新缓存内容(每一个缓存项都必须通过一个唯一的key来标识)。然后我们将这个自定制的输出缓存provider注册到web.config文件中,如下:

image

   在上面,我添加了一个输出缓存provider,名叫SampleCache,它由OutputCacheSample.dll程序集中的ScottOutputCache类实现。我同时也设置了ASP.NET的默认输出缓存provider为SampleCache,即通过上面的defaultProvider。

   现在,每当我在一个aspx页面添加下面的指令,页面内容就会通过ScottOutputCache缓存:

<%@ OutputCache Duration="60" VaryByParam="None"  %>

   类似的,如果我给一个action添加[OutputCache]属性,内容页将通过ScottOutputCache缓存:

[OutputCache(Duration=60)]
public ActionResult Browse(string category)
{
   return View();
}
 

定制使用哪个输出缓存Provider

   上面我只提供了一个默认的SampleCache输出缓存Provider。而开发人员实际上可以根据每个请求动态选择输出缓存Provider的。例如我们可以为首页和Top 10页面使用ASP.NET内置的内存provider(它超级迅速,因为内容存在内存中),而把不常用的请求页面缓存到磁盘。

   我们可以通过重载应用的Global.asax的GetOutputCacheProviderName()来实现上面的要求:

public class Global: System.Web.HttpApplication
{
   public override string GetOutputCacheProviderName(HttpContext context)\
   {
      if(context.Request.Path.EndsWith("Home.aspx")
      {
         return "AspNetInternalProvider";
      }
      else
      {
         return base.GetOutputCacheProviderName(context);
      }
   }
}

   这样我们单独为Home.aspx页面使用ASP.NET的内存缓存provider,而其他请求使用web.config中配置的缓存provider。

posted on 2013-01-09 21:33  feichexia  阅读(442)  评论(0编辑  收藏  举报