asp.Net 缓存技术

asp.net 2.0 支持的缓存包括
1 页面输出缓存
  页面输出缓存是将页面全部内容都保存在内存中,并用于完成客户端请求
 
  点击超连接,读入参数location=beijing ,页面每隔5秒刷新一次
  HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm3.aspx.cs" Inherits="WebForm3" %>
<%@ OutputCache Duration ="5" VaryByParam="location"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    
<title>页面缓存应用1</title>
    
<link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />    
</head>
<body>
    
<form id="form1" runat="server">
        
<div>
            
<fieldset style="width: 240px">
                
<legend class="mainTitle">设置页面输出缓存</legend>
                
<br />
                
<center>
                    
<asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center>
                
<br />
                    
<href="WebForm3.aspx?location=beijing" class="littleMainTitle">缓存时间</a><br />
            
</fieldset>
        
</div>
    
</form>
</body>
</html>
代码部分
  protected void Page_Load(object sender, EventArgs e)
    {
        /*
         * 页面缓存
         * 应用程序初始显示 的是停止执行缓存的时间,当用户刷新页面时,时间将随时变化
         * 单击"缓存时间超连接以后,页面重新定位,这时页面显示时间被缓存,数据过期时间为5秒,如果不断刷新该页面,那么每隔5秒刷新一次
         */
      
            //设置仅将缓存数据存储在服务器上
            Response.Cache.SetCacheability(HttpCacheability.Server);
            string temp_location = Request.QueryString["location"];
            //如果location为空,则不缓存,否则根据@ OutputCache指令声明执行缓存
            if (temp_location == null)
            {
                //停止当前响应的所有服务器缓存
                Response.Cache.SetNoServerCaching();
                Label1.Text = "停止缓存的时间:" + DateTime.Now.ToString();
            }
            else
            {
                Label1.Text = "设置了缓存的时间:" + DateTime.Now.ToString();
            }
      
        
    }
    
2 页面部分缓存
  实现方式: 控件缓存和缓存后替换
  控件缓存:允许将需要缓存的信息包含在一个用户控件内,然后将该控件标记为可缓存的,以此来缓存页面输出的部分内容
  缓存后替换,使用缓存后替换机制,可以将页配置为进行缓存,将页的个别部分标记为不可缓存.
 
  将整个页面输出缓存,然后实现缓存后替代
 
  HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm4.aspx.cs" Inherits="WebForm4" %>

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
</head>
<body>
   
<form id="form1" runat="server">
        
<div>
            
<fieldset style="width: 320px">
              
<legend class="mainTitle">使用Substitution控件实现页面部分缓存</legend>
              
<br />
                
<div class="littleMainTitle">
                    以下时间显示使用Substitution控件实现缓存后替换:
</div>
                
<asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
                      
</asp:Substitution>
               
                 
<hr />
                  
<div class="littleMainTitle">
                    以下时间显示使用页面输出缓存,缓存时间为5秒:
</div>
                    
<asp:Label ID="CachedDateLabel" runat="Server"></asp:Label>
                     
<br />
                
<center>
                
<asp:Button ID="RefreshButton" Text="刷新页面" runat="Server"></asp:Button></center>
                
                
<hr />
                
<br>
                
<div class="littleMainTitle">
                    以下时间显示使用Substitution控件API实现缓存后替换:
</div>
                
<%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
                
                
            
</fieldset>
        
</div>
    
</form>
</body>
</html>

代码部分
 protected void Page_Load(object sender, EventArgs e)
    
{
        CachedDateLabel.Text 
= DateTime.Now.ToString();
    }

    
public static string GetCurrentDateTime(HttpContext context)
    
{
        
return DateTime.Now.ToString();
    }

 这里把整个页面设置为页面缓存,然后
    <asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
                      </asp:Substitution>
                      和
   <%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
   实现了缓存替换
                     
3 应用程序数据缓存
  提供了一种编程方式,可以通过键/值方式对将任意数据存储在内存中.
  应用程序缓存的主要功能是在内存中存储各种与应用程序相关的对象 
  优点 :由asp.net管理缓存,他会在项过期,无效,或内存不足的时候移除缓存中的项,还可以配置应用程序缓存,以便在移除项的时候通知
  应用程序实现对缓存的增加,删除,检索
  对字符串数组tempArray进行操作,保存到数据缓存里面
  html代码
  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm5.aspx.cs" Inherits="WebForm5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
     
<title>应用程序数据缓存</title>
    
<link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
</head>
<body>
    
<form id="form1" runat="server">
        
<div>
            
<fieldset style="width: 310px">
                
<legend class="mainTitle">实现应用程序数据缓存</legend>
                
<br />
                
<div class="commonText">
                    字符串数组内容如下:
</div>
                
<div class="commonText" align="center">
                    北京,上海,广州,成都,深圳
</div>
                
<hr />
                
<div>
                    
<center>
                        
<asp:Button ID="btAdd" Text="添加" runat="Server" OnClick="AddItemToCache"></asp:Button>
                        
<asp:Button ID="btGet" Text="检索" runat="Server" OnClick="GetItemFromCache"></asp:Button>
                        
<asp:Button ID="btDel" Text="移除" runat="Server" OnClick="RemoveItemFromCache"></asp:Button>
                        
<div>
                            
<asp:Label ID="lbCacheInfo" runat="server" CssClass="commonText" ForeColor="red"></asp:Label></div>
                    
</center>
                
</div>
                
<hr />
                
<asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label>
            
</fieldset>
        
</div>
    
</form>
</body>
</html>

代码部分
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;

public partial class WebForm5 : System.Web.UI.Page
{

    
//声明变量    
    static CacheItemRemovedReason reason;
    
string[] tempArray = "北京""上海""广州""成都""深圳" };
    
//实现添加按钮的事件处理程序
    protected void AddItemToCache(object sender, EventArgs e)
    
{
        
//如果不存在,则添加;否则,只显示有关信息
        if (Cache["tempArray"== null)
        
{
            Cache.Add(
"tempArray", tempArray, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemoved));
            lbMessage.Text 
+= ">>>已经将字符串数组添加到缓存中 <br/>";
        }

        
else
        
{
            lbMessage.Text 
+= ">>>缓存中已经存在字符串数组 <br/>";
        }

        
//显示缓存信息
        DisplayCacheInfo();
    }

    
//实现检索按钮的事件处理程序
    protected void GetItemFromCache(object sender, EventArgs e)
    
{
        
//根据是否存在,显示信息
        if (Cache["tempArray"!= null)
        
{
            lbMessage.Text 
+= ">>>已检索到缓存中包括字符串数组 <br/>";
        }

        
else
        
{
            lbMessage.Text 
+= ">>>未检索到缓存中包括字符串数组 <br/>";
        }

        
//显示缓存信息
        DisplayCacheInfo();
    }

    
//实现删除按钮的事件处理程序
    protected void RemoveItemFromCache(object sender, EventArgs e)
    
{
        
//如果不存在,则显示信息;否则,调用方法移除
        if (Cache["tempArray"== null)
        
{
            lbMessage.Text 
+= ">>>未缓存字符串数组,无法删除<br/>";
        }

        
else
        
{
            Cache.Remove(
"tempArray");
            lbMessage.Text 
+= ">>>已经调用 CacheItemRemovedCallback 委托方法,缓存移除原因是:" + reason.ToString() + "<br/>";
            lbMessage.Text 
+= ">>>已删除字符串数组缓存<br/>";
        }

        
//显示缓存信息
        DisplayCacheInfo();
    }

    
// CacheItemRemovedCallback 委托方法
    private void ItemRemoved(String key, object value, CacheItemRemovedReason removedReason)
    
{
        reason 
= removedReason;
    }

    
private void DisplayCacheInfo()
    
{
        
string cacheCount = Cache.Count.ToString();
        lbCacheInfo.Text 
= "共包括" + cacheCount + "个缓存对象:";
        IDictionaryEnumerator CacheEnum 
= Cache.GetEnumerator();
        
while (CacheEnum.MoveNext())
        
{
            lbCacheInfo.Text 
+= CacheEnum.Key.ToString() + "";
        }

    }

    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

}

 
4 缓存依赖
  包括对XML,数据库(sql server的依赖)
  功能的核心是:sqlcachedependency类
 
  1 缓存依赖对xml操作
    把xml文件加载到界面缓存,然后进行操作
    xml(Computer.xml)文件如下:
  <Hardware>
  
<Item Choice="Intel" Price="1201" Url="PageA1.aspx" />
  
<Item Choice="AMD" Price="852" Url="PageB1.aspx" />
</Hardware>

Html界面
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm6.aspx.cs" Inherits="WebForm6" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
     
<title>实现自定义缓存依赖</title>
    
<link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<fieldset style="width: 300px">
      
<legend class="mainTitle">自定义缓存依赖应用</legend>
      
<br />
       
<div class="commonText">
       
<%--test--%>
                    
<center>
                        
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                            BorderStyle
="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            Width
="250px">
                            
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                        
</asp:GridView>
                    
</center>
       
</div>
       
       
       
<div>
                    
<center>
                        
<table width="250px">
                            
<tr>
                                
<td>
                                    Choice:
<asp:TextBox ID="txtChoice" runat="server" Width="40px"></asp:TextBox></td>
                                
<td>
                                    Price:
<asp:TextBox ID="txtPrice" runat="server" Width="40px"></asp:TextBox></td>
                                
<td>
                                    Url:
<asp:TextBox ID="txtUrl" runat="server" Width="40px"></asp:TextBox></td>
                            
</tr>
                            
<tr>
                                
<td colspan="3">
                                    
<asp:Button ID="btUpdate" Text="修改XML文件" runat="Server" OnClick="UpdateXmlFile"></asp:Button>
                               
</td> 
                            
</tr>
                            
<tr>
                                
<td colspan=3>
                                  
<asp:Button ID="btCacheRemove" Text="缓存清除" runat=server OnClick="btCacheRemove_Click" />
                                  
                                
</td>
                            
</tr>
                        
</table>
                    
</center>
                    
<div>
                        
<hr />
                        
<asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label></div>
      
</div>
                
    
</fieldset> 
    
</div>
    
</form>
</body>
</html>

代码部分
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.IO;

/*自定义缓存依赖应用*/
public partial class WebForm6 : System.Web.UI.Page
{

    
static CacheItemRemovedReason reason;

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!IsPostBack)
        
{

            LoadData();
        }

    }


    
//加载数据
    private void LoadData()
    
{
        DataView source;
        
//如果缓存为空,则添加缓存       
        if (Cache["tempData"== null)
        
{
            
            DataSet ds 
= new DataSet();
            
string filePath = Server.MapPath("../../App_Data/Computer.xml");
            ds.ReadXml(filePath);
            source 
= new DataView(ds.Tables[0]);

            
//
            CacheDependency dep = new CacheDependency(filePath, DateTime.Now);
            Cache.Insert(
"tempData", source, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CacheChanged));
            
//如果缓存依赖变化,则显示有关信息
            if (dep.HasChanged)
            
{
                lbMessage.Text 
= ">>> 缓存对象被移除,原因是" + reason.ToString() + "<br/>";
            }

            
 
            lbMessage.Text 
+= ">>> 显示XML文件数据.<br/>";
        }

        
else
        
{
            source 
= (DataView)Cache["tempData"];
            lbMessage.Text 
= ">>> 显示缓存对象中的数据.<br/>";
        }

        
//实现数据绑定
        GridView1.DataSource = source;
        GridView1.DataBind();
    }


    
// CacheItemRemovedCallback 委托方法
    private void CacheChanged(String key, object value, CacheItemRemovedReason removedReason)
    
{
        reason 
= removedReason;
    }


    
//实现对XMl文件的修改
    protected void UpdateXmlFile(object sender, EventArgs e)
    
{
        
////读取XML文件数据
        DataSet ds = new DataSet();
        
string filePath = Server.MapPath("../../App_Data/Computer.xml");
        ds.ReadXml(filePath);
        
//添加新数据行       
        try
        
{
            DataRow newLine 
= ds.Tables[0].NewRow();
            newLine[
"Choice"= txtChoice.Text;
            newLine[
"Price"= txtPrice.Text;
            newLine[
"Url"= txtUrl.Text;
            ds.Tables[
0].Rows.Add(newLine);
        }

        
catch
        
{
            lbMessage.Text 
= "无法正常添加新数据.<br/>";
        }

        
//通过新建和覆盖方式,将数据写入XML文件        
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
        ds.WriteXml(fs);
        fs.Close();
        
//移除缓存对象
        Cache.Remove("tempData");
        
//重新加载数据
        LoadData();
    }


    
protected void btCacheRemove_Click(object sender, EventArgs e)
    
{
        
//缓存清除
        if (Cache["tempData"]!=null)
        
{
            Cache.Remove(
"tempData"); 
        }


        
//Cache.Remove("tempData");  

    }

}


在 Page_设置断点,就可以看到xml加载缓存的效果

  2 缓存依赖对sql server操作
    把数据表加载到界面,然后查看,缓存更新
    (1)在数据库CPC_BusinessDB建立表 userinfo

 CREATE TABLE [dbo].[userinfo](
    
[UserId] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
    
[UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
    
[BranchId] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
    ) 
(2)对表增加数据
 (3)进入dos界面,输入命令
 aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -ed -t userinfo(表名)
 注意:
 关闭数据库依赖
 aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -dd
 关闭数据表依赖
 aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -t userinfo(表名) -dt 
 
 命令执行完成以后 在CPC_BusinessDB 下面增加 AspNet_SqlCacheTablesForChangeNotification表,显示缓存的 详细信息
 (4)编写代码
 web.config
 
 数据库连接字符串
<connectionStrings>    
    
<add name="LoggingDb" connectionString="user id=sa;password=XXXXXXXX;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB" providerName="System.Data.SqlClient"/>
  
</connectionStrings>

 缓存设置
   <caching>
      
      
<sqlCacheDependency enabled="true" pollTime="600">
        
<databases>
          
<add name="CPC_BusinessDB" connectionStringName="LoggingDb"/>
        
</databases>
      
</sqlCacheDependency>
    
</caching>

html部分
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm7.aspx.cs" Inherits="WebForm7" %>
<%@ OutputCache Duration="1000"  SqlDependency="CPC_BusinessDB:userinfo" VaryByParam="none" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
</head>
<body>
      
<form id="form1" runat="server">
        
<div>
            
<fieldset style="width: 260px">
                
<legend class="mainTitle">SQL数据缓存依赖应用</legend>
                
<br />
                
<div class="commonText">
                    
<center>
                        
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                            BorderStyle
="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            Width
="250px" AllowPaging="True" AutoGenerateColumns="False" 
                            PageSize
="6">
                            
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                            
<Columns>
                                
<asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="True" SortExpression="userid" />
                                
<asp:BoundField DataField="username" HeaderText="username"   SortExpression="username"/>
                                
<asp:BoundField DataField="branchid" HeaderText="branchid"   SortExpression="branchid" />
                            
</Columns>
                        
</asp:GridView>
                       
                    
</center>
                
</div>
                
<div>
                    
<center>
                        
<asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label>&nbsp;</center>
                
</div>
            
</fieldset>
        
</div>
    
</form>
</body>
</html>

代码部分
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class WebForm7 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        lbMessage.Text 
= "页面刷新时间:" + DateTime.Now.ToString();
        bind_data();
    }


    
private void bind_data()
    
{
        
        
string str_Conn = "user id=sa;password=19791225;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB";
        
try
        
{
            DataSet ds
=new DataSet() ;
            SqlConnection objConn 
= new SqlConnection(str_Conn);
            
//objConn.Open();

            
string str_sql = "select userid,username,branchid from userinfo";
            SqlCommand objComm 
= new SqlCommand(str_sql, objConn);
            SqlDataAdapter objAdapter 
= new SqlDataAdapter(objComm);
            objAdapter.Fill(ds, 
"userinfo");
            GridView1.DataSource 
= ds.Tables[0];
            GridView1.DataBind();
            
//objConn.Close();
        }

        
catch (Exception exc)
        
{
            
//MessageBox.Show(exc.Message);

        }




    }


}


这样实现SQL数据缓存依赖
StyleSheet.css 文件
body
{
}

.mainTitle
{
    font-size
: 12pt;
    font-weight
: bold;
    font-family
: 宋体;
}

.commonText
{
    font-size
: 10pt;
    font-family
: 宋体;
}

.littleMainTitle
{
    font-size
: 10pt;
    font-weight
: bold;
    font-family
: 宋体;
}


posted @ 2007-06-05 12:53  jhtchina  阅读(3436)  评论(0)    收藏  举报