好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

数据缓存技术及代码详解

数据缓存技术及代码详解

1.缓存概述
  •为什么使用缓存
    – 应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能
  • 缓存机制分类介绍
    – 应用程序缓存
    – 页输出缓存

2.应用程序缓存的机制
  • 应用程序缓存是由System.Web.Caching.Cache 类实现的,缓存实例(Cache 对象)是每个应用程序专
    用的,并且每个应用只有一个,通过Page类或UserControl类的Cache 属性公开
   • 缓存生存期依赖于应用程序的生存期,当重新启动应用程序后,将重新创建Cache 对象,也就是说缓存数据将被清空

3.如何将项添加到缓存中 
  • 添加缓存项
  • 设置缓存依赖项  
  • 设置缓存过期策略
  • 设置缓存优先级
4.设置缓存依赖项
  • 为什么要设置依赖项
  • 依赖项分类
    – 键依赖项
    – 文件依赖项
    –SQL 依赖项
    – 聚合依赖项
    – 自定义依赖项
  • 添加缓存项的文件依赖项
    Cache.Insert("FinanceData", "Cached Item 4",
      new System Web Caching CacheDependency(Server.MapPath( "XMLData.xml " ))); 
  • 添加缓存项的SQL 依赖项
    – 使用SqlCacheDependency 对象来创建依赖于数据库表中的记录
    – 在Web.config 文件的caching节点定义缓存使用的数据库名称及连接字符串
    – 使用代码依赖于该连接对应数据库的某个表的缓存项
      Cache.Insert("cacheitem1", "Cache Item 1", 
        new SqlCacheDependency("AdvWorks", "Product"));
5.从缓存中删除项时通知应用程序
  • CacheItemRemovedCallback 委托
    – 该委托定义编写事件处理程序时使用的签名,当对从缓存中删除项进行响应时会调用此事件处理程序
  • CacheItemRemovedReason 枚举
    – 用于指定删除缓存项的原因

6.实例演示(使用CacheDependency监视文件变化)

  a)新建一个CacheUtil类,来处理Cache的常见操作,代码如下: 

View Code

  public   class   CacheUtil
    {
          public   static   void   AddCache()
        {
              var  ds =  new   System.Data.DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(  "  ~/Employees.xml  "  ));

            HttpContext.Current.Cache.Add(  "  EmployeeSet  " , ds,  new  CacheDependency(HttpContext.Current.Server.MapPath( "  ~/Employees.xml  "  ))
                , DateTime.Now.AddHours(  1  ), Cache.NoSlidingExpiration, CacheItemPriority.High
                , EmployeeSetCacheItemRemoved);
        }

          public   static   void  EmployeeSetCacheItemRemoved( string  key,  object   value, CacheItemRemovedReason reason)
        {
              switch   (reason)
            {
                  case   CacheItemRemovedReason.DependencyChanged:
                    AddCache();
                      break  ;
            }
        }
    } 

   b)修改Global.asax.cs的Application_Start,在网站启动时,添加Cache

View Code

 void  Application_Start( object   sender, EventArgs e)
        {
              //  在应用程序启动时运行的代码 
             CacheUtil.AddCache();
        } 

  c)修改Default.aspx.cs的Page_Load

View Code

 protected   void  Page_Load( object   sender, EventArgs e)
        {
              if  (Cache[ "  EmployeeSet  " ] ==  null  )
            {
                CacheUtil.AddCache();
            }
              var  ds = (DataSet)Cache[ "  EmployeeSet  "  ];
            GridView1.DataSource  = ds.Tables[ 0  ];
            GridView1.DataBind();
        } 

   d)效果图:

  当修改Employees.xml,保存后,缓存会接到文件改变通知,重新加载数据

7.实例演示(使用SqlCacheDependency监视数据库表变化)

  a)新建一个页面SqlCacheTest.aspx,使用模板页

  b)启用数据库缓存依赖项

  此时会在数据库Student中的表Contact生成一个触发器和一堆存储过程:

  c)配置web.Config

    在  <system.web>节点下,加入:

View Code

  <  caching  > 
       <  sqlCacheDependency   enabled  ="true"  > 
         <  databases  > 
           <  add   name  ="Student"   connectionStringName  ="Student"  /> 
         </  databases  > 
       </  sqlCacheDependency  > 
     </  caching  > 

    设置connectionStringName:

View Code

 <  connectionStrings  > 
     <  add   name  ="Student"  
         connectionString  ="server=.;database=Student;Integrated Security=SSPI"  
         providerName  ="System.Data.SqlClient"   /> 
   </  connectionStrings  > 

  d)修改CacheUtil.cs

View Code

   public   class   CacheUtil
    {
          public   static   void   AddCache()
        {
              var  ds =  new   DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(  "  ~/Employees.xml  "  ));
            
            HttpContext.Current.Cache.Add(  "  EmployeeSet  " , ds,  new  CacheDependency(HttpContext.Current.Server.MapPath( "  ~/Employees.xml  "  ))
                ,DateTime.Now.AddHours(  1  ),Cache.NoSlidingExpiration, CacheItemPriority.High
                ,EmployeeSetCacheItemRemoved);
        }

          public   static   void  EmployeeSetCacheItemRemoved( string  key,  object   value, CacheItemRemovedReason reason)
        {
              switch   (reason)
            {
                  case   CacheItemRemovedReason.DependencyChanged:
                    AddCache();
                      break  ;
            }
        }

          public   static   void   AddSqlCache()
        {
              var  dt =  new   DataTable();
              var  da =  new  SqlDataAdapter( "  select * from Contact  " , ConfigurationManager.ConnectionStrings[ "  Student  "  ].ConnectionString);
            da.Fill(dt);
            HttpContext.Current.Cache.Add(  "  Contact  "  
                                          , dt
                                          ,   new  SqlCacheDependency( "  Student  " ,  "  Contact  "  )
                                          , DateTime.Now.AddDays(  1  )
                                          , Cache.NoSlidingExpiration
                                          , CacheItemPriority.High
                                          , ContactCacheItemRemoved);
        }

          public   static   void  ContactCacheItemRemoved( string  key,  object   value, CacheItemRemovedReason reason)
        {
              switch   (reason)
            {
                  case   CacheItemRemovedReason.DependencyChanged:
                    AddSqlCache();
                      break  ;
            }
        }
    } 

  e)修改Global.asax.cs的Application_Start

View Code

   void  Application_Start( object   sender, EventArgs e)
        {
              //  在应用程序启动时运行的代码 
             CacheUtil.AddCache();
            CacheUtil.AddSqlCache();
        } 

  f)修改SqlCacheTest.aspx.cs的Page_Load

View Code

  protected   void  Page_Load( object   sender, EventArgs e)
        {
              if  (Cache[ "  Contact  " ] ==  null  )
            {
                CacheUtil.AddSqlCache();
            }
              var  dt = (DataTable)Cache[ "  Contact  "  ];
            GridView1.DataSource  =  dt;
            GridView1.DataBind();
        } 

  g)效果图

  当我们在SSMS中修改数据库表的数据后,停小段时间,刷新页面

8)页输出缓存概述 
  • 页输出缓存是指在缓存ASP.NET  页所生成的部分响应或所有响应
  • 提高Web应用程序的性能
  • 提高Web服务器的吞吐量
9)SqlCacheDependency 
  • System.Web.Caching.SqlCacheDependency
  – 创建依赖于数据库中表或行的缓存项
    – <%@ OutputCache Duration="30" 
      VaryByParam="none“ SqlDependency="Student:Contact" %>
10)部分页缓存 
  • 控件缓存
    – 控件缓存(也称为片段缓存),可以通过创建 控件缓存(也称为片段缓存),用户控件来包含缓存的内容,然后将用户控件
      标记为可缓存来缓存部分页输出
  • 缓存后替换
    – 以声明方式使用Substitution 控件
    – 以编程方式使用Substitution 控件API
    – 以隐式方式使用AdRotator 控件
11)DataSource 缓存
  • 启用XxxDataSource 当中的缓存
  • 缓存单个数据源控件

12)SqlCacheDependency页面输出缓存实例

  a)新建文件夹:OutputCache

  b)在文件夹OutputCache中新建SqlCacheDependency.aspx 

View Code

<%@ Page Title= ""  Language= "  C#  "  MasterPageFile= "  ~/Site.Master  "  AutoEventWireup= "  true  "  CodeBehind= "  SqlCacheDependency.aspx.cs  "  Inherits= "  UseCache.OutputCache.SqlCacheDependency  "  %>

<%@ OutputCache Duration= "  3600  "  VaryByParam= "  none  "  SqlDependency= "  Student:Contact  "  %>

<asp:Content ID= "  Content1  "  ContentPlaceHolderID= "  HeadContent  "  runat= "  server  " >
</asp:Content>
<asp:Content ID= "  Content2  "  ContentPlaceHolderID= "  MainContent  "  runat= "  server  " >
        <asp:Label ID= "  Label1  "  runat= "  server  "  Text= "  Label  " ></asp:Label>

        <br />
        <asp:GridView ID= "  GridView1  "  runat= "  server  " >
        </asp:GridView>
        <br />

</asp:Content>

  后台代码:

View Code

 public   partial   class   SqlCacheDependency : System.Web.UI.Page
    {
          protected   void  Page_Load( object   sender, EventArgs e)
        {
            Label1.Text  =  DateTime.Now.ToLongTimeString();
              var  dt =  new   DataTable();
              var  da =  new  SqlDataAdapter( "  select * from Contact  "  ,
                                        ConfigurationManager.ConnectionStrings[  "  Student  "  ].ConnectionString);
            da.Fill(dt);
            GridView1.DataSource  =  dt;
            GridView1.DataBind();
        }
    } 

13)使用用户控件

  a)在文件夹OutputCache中新建LableControl.ascx

View Code

<%@ Control Language= "  C#  "  AutoEventWireup= "  true  "  CodeBehind= "  LableControl.ascx.cs  "  Inherits= "  UseCache.OutputCache.LableControl  "  %>
<%@ OutputCache Duration= "  5  "  VaryByParam= "  none  "  %>

 <asp:Label ID= "  Label1  "  runat= "  server  "  Text= "  Label  " ></asp:Label>

  后台代码:

View Code

  protected   void  Page_Load( object   sender, EventArgs e)
        {
            Label1.Text  =  DateTime.Now.ToLongTimeString();
        } 

  b)在文件夹OutputCache中新建PartialCachePage.aspx

View Code

<%@ Page Title= ""  Language= "  C#  "  MasterPageFile= "  ~/Site.Master  "  AutoEventWireup= "  true  "  CodeBehind= "  PartialCachePage.aspx.cs  "  Inherits= "  UseCache.OutputCache.PartialCachePage  "  %>
<%@ Register src= "  LableControl.ascx  "  tagname= "  GridControl  "  tagprefix= "  uc1  "  %>

<asp:Content ID= "  Content1  "  ContentPlaceHolderID= "  HeadContent  "  runat= "  server  " >
</asp:Content>
<asp:Content ID= "  Content2  "  ContentPlaceHolderID= "  MainContent  "  runat= "  server  " >
        <asp:Label ID= "  Label1  "  runat= "  server  "  Text= "  Label  " ></asp:Label><br /> 

         LableControl用户控件缓存5秒: <uc1:GridControl ID= "  LableControl1  "  runat= "  server  "  />
</asp:Content>

  后台代码:

View Code

  protected   void  Page_Load( object   sender, EventArgs e)
        {
            Label1.Text  =  DateTime.Now.ToLongTimeString();
        } 

14)使用SqlDataSource

  在文件夹OutputCache中新建SqlDataSourceCache.aspx

  转载请注明出处:http://www.cnblogs.com/refactor

 

分类:  C# ,  Web

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于数据缓存技术及代码详解的详细内容...

  阅读:53次