ASP.NET 2.0 --Caching For performance

来源:互联网 发布:用友js面试题 编辑:程序博客网 时间:2024/04/26 01:31

Output Caching

设置缓存时有两种方法:基于底层的API技术和基于高层的@OutputCaching 
① <@ OutputCaching Duration="60" VaryByParam="none">可以通过参数VaryByParam缓存不同的页面

②默认情况下,Output Cache 会被缓存到硬盘上,通过修改diskcacheenable的属性来设置其是否缓存,还可以通过在web config里配置缓存文件大小!
<@ OutputCache Duration="3600" DiskCacheEnable="true" VaryByParam="name">
通过使用Substitution来实现缓存

使用API定制缓存
通过设置System.Web.HttpCachePolicy属性来配置下面语句
Response.Cache.SetExpires(Now .AddSeconds(60))
Response.Cache.SetCacheability(HttpCacheablity.Public)

Response.Cache.SetSlidingExpiration(True);   //每次请求页时都重新设置过期时间

从 ASP 移植过来的应用程序可能已用 ASP 属性设置了缓存策略;例如:
Response.CacheControl = "Public";
Response.Expires = 60;

Page Fragment Caching

专门用于缓存用户控件,通过指定返回参数,来决定被缓存的部分,使用语句VatyByParam语句指定根据参数来改变。


Data Cache

当首次被请求时,它指出数据是从数据库服务器中显式检索的。刷新页面后,页说明使用的是缓存副本。

  <script language="C#" runat="server">

   
void Page_Load(Object Src, EventArgs E) {

      DataView Source;

      Source = (DataView)Cache["MyDataSet"];


      if (Source == null) {

        SqlConnection myConnection = new SqlConnection("server=(local)//NetSDK;database=pubs;Trusted_Connection=yes");
        SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);

        DataSet ds = new DataSet();
        myCommand.Fill(ds, "作者");

        Source = new DataView(ds.Tables["作者"]);
        Cache["MyDataSet"] = Source;


        CacheMsg.Text = "显式创建的数据集";
      }
      else {
        CacheMsg.Text = "从缓存中检索到的数据集";
      }

      MyDataGrid.DataSource=Source;
      MyDataGrid.DataBind();
    }

  </script>

   当缓存数据时,XML 文件被添加为依赖项。

文件依赖项是通过使用 Cache.Insert 并提供引用 XML 文件的 CacheDependency 对象添加的。

Cache.Insert("MyData", Source,         new CacheDependency(Server.MapPath("authors.xml")));

 

缓存项可以依赖于一个或多个文件或键。如前面提到的,应用程序也可以设置缓存项的过期策略。下列代码设置绝对的缓存过期时间。

Cache.Insert("MyData", Source, null,
             DateTime.Now.AddHours(1), TimeSpan.Zero);

相关的参数是对 DateTime.Now.AddHours(1)的调用,DateTime.Now.AddHours(1) 指示该项自插入后一小时过期。最后一个参数 TimeSpan.Zero 表示此项没有相对过期策略。

下列代码显示如何设置相对过期策略。它插入一个项,该项自上次访问后 20 分钟过期。注意 DateTime.MaxValue 的使用,它表示此项没有绝对过期策略。

Cache.Insert("MyData", Source, null, DateTime.MaxValue,             TimeSpan.FromMinutes(20));

SQL  Caching

配置连接池

 

Caching  Configuration缓存配置

<caching>
   <outputCache>
    <diskCache enabled="true" maxSizePerApp="2" />
   </outputCache>
   <outputCacheSettings>
    <outputCacheProfiles>
     <add name="CacheFor60Seconds" duration="60" />
    </outputCacheProfiles>
   </outputCacheSettings>

  </caching>