分类广告


推荐文章

  • 没有找到任何内容!
您当前的位置:中国站长下载网络编程ASP专区 → 文章内容

ASP.NET 2.0数据缓存功能简介

  • 作者:风未起时    来源:中国站长学院    发布时间:2005-7-3 9:37:56
  • 字体大小:

接下来,我们用visual web developer 2005 beta,来创建一个website,往其中增加一个label标签,以显示当前执行的时间。并往其中增加一个gridview控件,用来显示来自pubs数据库的表authors,代码如下:

<%@ Page Language="VB" AutoEventWireup="false" CompileWith="Default.aspx.vb" ClassName="Default_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
 <asp:Label ID="Label1" Runat="server" Text="Label" Width="74px" Height="19px"></asp:Label> 
<br />
<asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1">
</asp:GridView>
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT * FROM authors"
ConnectionString="Initial Catalog=pubs;Data Source=localhost;user id=sa;password=123456">
</asp:SqlDataSource>
</form>
</body>
</html>


  在default.aspx.vb的代码的page_load事件中,加入以下代码

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = CType(System.DateTime.Now(), String)
End Sub


  接下来,我们开始配置web.config文件。我们采用的配置文件如下:

<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="PubsConn" connectionString="Initial Catalog=pubs;Data Source=(local);user id=sa;password=123456"/>
</connectionStrings>
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="500">
<databases>
<add name="Pubs" connectionStringName="PubsConn"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
</configuration>


  其中,要注意的是polltime参数,polltime参数是毫秒,最小值为500,该参数的意义时设置系统多长时间去检查一次cache中的数据是否需要更新。而<database>标签内必须注明需要用到的数据库连接字符串,必须和之前<connectionStrings>中定义的名称相符合(如本例中,connectionstring的名称是pubsconn。

  最后,我们在程序的首部,加入页面缓存的定义语句如下:

<%@ outputcache duration="60" varybyparam="none" sqldependency="Pubs:authors" %>

  上面的语句,则定义了页面输出缓存为1分钟,并且使用sqldependency,sqldependency的属性中,以“名称:表名”的形式定义,其中的名称,就是刚才我们在web.config中定义的<databases>中的名称,这里是pubs。“Pubs:authors”中的authors,则是要使用sqldependency的表名authors表。在这里要注意的是,虽然我们是用vb.net,但sqldependency属性中的参数注定是大小写敏感的,如“Pubs:authors”中的表名authors必须和用Aspnet_regsql在命令行下定义的表名authors一样。

  运行我们的程序,先不修改数据库中的数据。如下图:


  我们不断刷新该应用,会发现由于使用了缓存功能,上面的时间是不变的。现在我们打开sql server,修改其中的au_id为172-32-1176的作者名white,将其改为RED,之后再刷新程序,看到了么?由于使用了sqldependency的功能,马上缓存中反映出新修改的数据了:
  

上一页  [1] [2]