ASP.NET初识8

1、缓存机制
  输出缓存
  页输出缓存对于那些不经常更改,但需要大量处理处理才能创建的页特别有用
  应用程序缓存(数据缓存)
  手工编写代码实现
2、实现页面缓存,在页面声明区添加一条OutputCache的声明
  Duration属性用于指定当前页面要缓存的时间,以秒为单位
  86400为缓存一天
  VaryByParam表示根据指定的查询字符串来缓存页面
    none:表示不根据查询字符串缓存,通常用于静态页面中
    *表示根据任何查询字符串缓存
  指定多个查询字符串使用分号隔开,如"ProductID;CategoryID"
3、使用缓存配置<%@ OutputCache CacheProfile="ProductCache" %>
  <configuration>
    <system.web>
      <Caching>
        <outputCacheSettings>
          <outputCacheProfiles>
            <add name="ProductCache" duration="3600" varyByParam="none" />
            <add name="1hoursCache" duration="5000" varyByCustom="browser" />
          </outputCacheProfiles>
        <outputCacheSettings>
      </Caching>
    </system.web>
  </configuration>
  
4、使用HttpCachePolicy类控制缓存
  Response.Cache.SetCacheability(HttpCachePolicy.Public);
  Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
  Response.Cache.SetValidUntilExpires(true);
  根据浏览器的类型缓存
  Response.Cache.SetExpires(DateTime.Now.AddMinutes(1d));
  Response.Cache.SetCacheability(HttpCacheability.Public);
  Response.Cache.SetValidUntilExpires(true);
  Response.Cache.SetVaryByCustom("browser");
  使用代码控制缓存不是很好的设计 
5、使用Cache类缓存应用程序数据时最灵活的一种缓存类型 
  通用原则:不要随意缓存数据,而应该值回村一些特别占用资源的数据
  Cache对象是线程安全的,在编写多线程应用时不需要显示的加锁或解锁对象
  Cache中的对象如果过期,则会自动被移除,因此在从Cache对象中获取数据时,需要先判断是否存在所要获取对象
  Cache对象支持缓存以来,可以将Cache对象与一个文件、一个数据库表或其他任何类型的资源相关联,如果发生改变,Cache对象可以自动的被移除或更新 
6、缓存依赖类
  CacheDependency:允许基于文件或其他缓存创建依赖
  SqlCacheDependency:基于SqlServer的表或者是一个Sql Server查询的依赖
  AggregateCacheDependency:基于多个缓存依赖项的依赖,比如可以同时组合SQL依赖和文件依赖 
7、配置SQL缓存依赖
  指定要使用缓存依赖的数据库和一个或多个数据表,使用aspnet_regsql.exe命令行工具进行配置
  配置数据库支持缓存依赖:aspnet_regsql.exe -S localhost -U sa -d Northwind -ed
  为Products表启用缓存依赖:aspnet_regsql.exe -S localhost -U sa -d Northwind -t Products -et
  在web.config文件中配置缓存依赖
  <caching>
    <sqlCacheDependency enabled="true" pollTime="3600">
      <database>
        <add name="NorthwindDatabase" connectionStringName="NorthwindConnectionString" />
      </database>
    </sqlCacheDependency>
  </caching>
8、在程序中使用SQL缓存依赖
  在输出缓存中使用缓存依赖
  <%@ OutputCache Duration="1200"  SqlDependency="NorthwindDataBase:Products" %>
  在SqldataSource控件中使用SQL缓存依赖,只需为SqlCacheDependency属性赋相同的值
  SqlDependency="NorthwindDataBase:Products"
  在Cache对象中使用SQL缓存依赖,需要实例化一个SqlDependency对象
  protected void EnableDenpendency()
  {
    DataSet ds = (DataSet)Cache["ProductInfo"];
    if(ds == null)
    {
      ds =GetProductDataSet();
      SqlCacheDependency sqldependency = new  SqlCacheDependency("NorthwindDataBase","Products");
      Cache.Insert("ProductInfo",ds,sqldependency);) 
    }
  }
posted @ 2011-06-25 12:53  常伟华  阅读(241)  评论(0编辑  收藏  举报