数据缓存简介:
缓存是一种在计算机中广泛用来提高性能的技术
在Web应用程序的上下文中,缓存用于在Http请求间保留页或者数据,并在无需新创建的情况下多次使用它们
目的:节省应用程序处理时间和资源
1.页面输出缓存
- @OutputCache指令
<%@ OutputCache Duration="1"VaryByParam="none"%>
Duration表示缓存时间 VaryByParam表示改变所要缓存的输出的形参。
对于OutputCache指令 Duration和VaryByParam两个属性是必须的。
- HttpCachePolicy类
后台代码:
//页面输出缓存时间是30秒
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
//缓存过期的绝对时间是当日下午7点整
Response.Cache.SetExpires(DateTime.Parse("19:00:00"));
//设置页面缓存级别
Response.Cache.SetCacheability(HttpCacheability.Public);
2.页面部分缓存
- 控件缓存
添加 Web用户控件
WebUserControl1.ascx前台代码:
<%@ OutputCacheDuration="60"VaryByParam="none"%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="score" HeaderText="score" SortExpression="score" />
<asp:BoundField DataField="subject" HeaderText="subject"
SortExpression="subject" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ConnectionStrings:StudentsConnectionString %>"
SelectCommand="SELECT [score], [subject] FROM [StuMark]">
</asp:SqlDataSource>
WebUserControl1.ascx后台代码:
private int _sid;
public int SID
{
get
{
return_sid;
}
set
{
_sid = value;
SqlDataSource1.SelectCommand = "SELECT [score], [subject] FROM [StuMark] where[sid]=" + _sid;
SqlDataSource1.DataBind();
}
}
用户控件.aspx中 前台代码:
将WebUserControl1.ascx拖入:
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" SID="1"/>
<uc1:WebUserControl1 ID="WebUserControl1" runat="server" SID="2"/>
运行后如图所示:
- 缓存后替换
1)在使用Substitution时,首先我们将整个页面缓存起来,然后将页面中需要动态改变内容的地方用
Substitution控件代替即可
2)Substitution控件需要设置一个重要属性MethodName,该属性用于获取或者设置当Substitution控件执
行时为回调而调用的方法名称
3)回调方法必须要符合3点:
方法必须被定义为静态方法
方法必须接受HttpContext类型的参数
方法必须返回String类型的值
添加新项:缓存后替换.aspx
1)在页面代码中添加@OutputCache指令,代码如下:
<%@ OutputCacheDuration="1"VaryByParam="none"%>
2)在页面中加入服务器控件,完成布局,代码如下:
<%@ PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm2.aspx.cs"Inherits="WebApplication1.WebForm2"%>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 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>
<legend>缓存后替换</legend>
<div>
使用Substitution:<br>
<asp:Substitution ID="Substitution1" runat="server" MethodName="GetTime" />
<hr />
普通时间:<br>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</fieldset>
</div>
</form>
</body>
</html>
3)后台代码中,添加GetTime方法,完成时间的显示。完整代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protectedvoid Page_Load(objectsender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
//Substitution调用的事件
public static stringGetTime(HttpContext context)
{
returnDateTime.Now.ToLongTimeString();
}
}
}
4)保存代码,运行调试,运行结果如图所示:
3.应用程序数据缓存:
1)应用程序数据缓存的主要功能是在内存中存储各种与应用程序相关的对象。通常这些对象都需要耗费大量
的服务器资源才能创建
2)应用程序数据缓存由Cache类实现
方 法 | 描 述 |
Add | 将指定项添加到Cache对象,该对象具有依赖项、过期和优先级策略以及一个委托(可用于在从Cache移除插入项时通知应用程序)。 |
Insert | 向 Cache 对象插入项。使用此方法的某一版本改写具有相同 key 参数的现有 Cache 项。 |
Remove | 从应用程序的 Cache 对象移除指定项。 |
3)检索应用程序缓存对象
从缓存中检索应用程序数据缓存对象的方法,我们通常可以使用2种方法:
(1) 指定键名
string categoryId =(string)Cache["categoryId"];
(2) 使Cache类的Get方法
string categoryId = (string)Cache.Get("categoryId");
- 添加新项:应用程序缓存实例.aspx
1)在页面中加入Button控件,完成布局,代码如下:
<%@ PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm3.aspx.cs"Inherits="WebApplication1.WebForm3"%>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 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>
<asp:Button ID="btADD" runat="server" Text="CacheADD" OnClick="btADD_Click" /><br />
<br />
<asp:Button ID="btINSERT" runat="server" Text="CacheINSERT" OnClick="btINSERT_Click" /><br />
<br />
<asp:Button ID="byGET" runat="server" Text="获取Cache" OnClick="byGET_Click" />
</div>
</form>
</body>
</html>
2)后台代码中,添加按钮事件,完整代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
namespace WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page
{
protectedvoid Page_Load(objectsender, EventArgs e)
{
}
// Add方法
protectedvoid btADD_Click(objectsender, EventArgs e)
{
//Add方法添加缓存
Cache.Add("qwe","ADD CACHE", null, DateTime.Now.AddSeconds(5),Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
//Insert方法
protectedvoid btINSERT_Click(objectsender, EventArgs e)
{
//Insert方法添加缓存
Cache.Insert("qwe", "INSERTCACHE", null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration);
}
//查看缓存
protectedvoid byGET_Click(objectsender, EventArgs e)
{
//判断当前缓存是否过期
if(Cache["qwe"] != null)
{
stringstr = (string)Cache["qwe"];
//打印
Response.Write(str);
}
else
{
Response.Write("缓存无效,已过期");
}
}
}
}
3)保存代码,运行调试,运行结果如图所示:
获取 CacheADD:
获取CacheINSERT:
5秒后再次获取: