1. 数据缓存技术
2. @OutputCache 指令
<%@ OutputCache Duration="60" VaryByParam="none" %>
Duration属性表示页面或用户控件的缓存时间。
VaryByParam改变所要缓存输出的形参。
对于OutputCache指令 Duration和VaryByParam两个属性是必须的
3.HttpCachePolicy类
protected void Page_Load(object sender, EventArgs e)
{
//页面输出缓存时间是30秒
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
//缓存过期的绝对时间
Response.Cache.SetExpires(DateTime.Parse("09:22:00"));
//设置页面缓存级别
Response.Cache.SetCacheability(HttpCacheability.Public);
}
4. 页面部分缓存
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
4.3 缓存后替换Substitution
事例:
页面中添加@ OutputCache指令
<%@ OutputCache Duration="10" VaryByParam="none" %>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>使用Substitution控件实现缓存后替换 </legend>
<br />
<div>
以下时间显示,使用了Substitution控件
</div>
<asp:Substitution ID="SubTime" MethodName="GetTime" runat="server" />
<hr style="color: Red" />
<div>
以下时间显示为页面缓存,缓存时间为10秒</div>
<asp:Label ID="labTime" runat="server">
</asp:Label><br />
</fieldset>
</div>
</form>
在后台代码中添加GetTime方法,完成时间显示。
protected void Page_Load(object sender, EventArgs e)
{
this.labTime.Text = DateTime.Now.ToLongTimeString();
}
public static string GetTime(HttpContext context)
{
return DateTime.Now.ToLongTimeString();
}
5. 应用程序数据缓存
方法 | 描述 |
Add | 将指定项添加到Cache对象,该对象具有依赖项、过期和优先级策略以及一个委托(可用于在从Cache移除插入项时通知应用程序)。 |
Insert | 向 Cache 对象插入项。使用此方法的某一版本改写具有相同 key 参数的现有 Cache 项。 |
Remove | 从应用程序的 Cache 对象移除指定项。 |
5.1 ADD方法
public Object Add(
stringkey, //缓存的键
Objectvalue, //要添加的缓存项
CacheDependencydependencies, //依赖项
DateTimeabsoluteExpiration, //设置的过期移除时间
TimeSpanslidingExpiration, //最后一次访问时间过期时间的间隔
CacheItemPrioritypriority, //对象的相对成本
CacheItemRemovedCallbackonRemoveCallback//移除时要调用的委托
)
5.2Insert方法
Insert(String, Object)
Insert(String, Object, CacheDependency)
Insert(String, Object, CacheDependency, DateTime, TimeSpan)
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)
//代码示例将有一分钟绝对过期时间的项添加到缓存中
Cache.Insert("CacheItem6", "Cached Item 6",
null, DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);
5.3检索应用程序缓存对象
string categoryId = (string)Cache["categoryId"];
string categoryId = (string)Cache.Get("categoryId");
(2)应用程序缓存事例
添加按钮
添加按钮事件
// Add方法
protected void BtnCacheAdd_Click(object sender, EventArgs e)
{
//Add方法添加缓存
Cache.Add("aaa", "我爱你中国", null, DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
//Insert方法
protected void BtnCacheInsert_Click(object sender, EventArgs e)
{
//Insert方法添加缓存
Cache.Insert("aaa", "我爱你北京", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration);
}
//查看缓存
protected void Button1_Click(object sender, EventArgs e)
{
//查看缓存
string cacheContext = "";
//判断当前缓存是否过期
if (Cache["aaa"] != null)
{
cacheContext = Cache["aaa"].ToString();
//打印
Response.Write(cacheContext);
}
else
{
Response.Write("已过期!!");
}
}
6.缓存依赖
<form id="form1" runat="server">
<div align="center">
<asp:GridView ID="gvGoods" runat="server" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="142px" Width="583px">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<sortedascendingcellstyle backcolor="#FEFCEB" />
<sortedascendingheaderstyle backcolor="#AF0101" />
<sorteddescendingcellstyle backcolor="#F6F0C0" />
<sorteddescendingheaderstyle backcolor="#7E0000" />
</asp:GridView>
品牌:<asp:TextBox ID="txtBread" runat="server"></asp:TextBox>
型号:<asp:TextBox ID="txtType" runat="server"></asp:TextBox>
数量:<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox><br>
<asp:Button ID="BtnAdd" runat="server" Text="添加数据" OnClick="BtnAdd_Click" />
</div>
</form>
后台事件代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//把XML数据取出作为数据源
LoadGVGoods();
}
}
protected void LoadGVGoods()
{
DataSet ds;
//判断缓存是否为空
if (Cache["XMLData"] == null)
{
ds = new DataSet();
//获取XML路径
string filePath = Server.MapPath("~/XMLFile.xml");
//读取XML文件,并得到数据
ds.ReadXml(filePath);
//定义缓存依赖
CacheDependency cd = new CacheDependency(filePath, DateTime.Now);
//添加缓存
Cache.Insert("XMLData", ds, cd);
}
else
{
ds = (DataSet)Cache["XMLData"];
}
//绑定数据源
this.gvGoods.DataSource = ds;
//重新绑定
this.gvGoods.DataBind();
}
//添加数据到XML文件中
protected void BtnAdd_Click(object sender, EventArgs e)
{
//引用System.Xml
XmlDocument xd = new XmlDocument();
//加载XML文件
xd.Load(Server.MapPath("~/XMLFile.xml"));
//创建节点
XmlElement xe = xd.CreateElement("Item");
xe.SetAttribute("Breed", this.txtBread.Text);
xe.SetAttribute("Type", this.txtType.Text);
xe.SetAttribute("Number", this.txtNumber.Text);
//加入到XML中
xd.DocumentElement.AppendChild(xe);
//把添加好的数据保存回原文件
xd.Save(Server.MapPath("~/XMLFile.xml"));
//移除缓存
Cache.Remove("XMLData");
//调用LoadGVGoods
LoadGVGoods();
}
6.2实现SQL数据缓存依赖
//SqlCacheDependency类构造函数
//构造函数一
public SqlCacheDependency(SqlCommand sqlcmd);
//构造函数二
public SqlCacheDependency(string dbEntryName,string tableName);
注意事项:
聚合缓存依赖
//自定义文件缓存依赖
CacheDependencydep1 = new CacheDependency(fileName);
//创建SQL数据缓存依赖,cmd是一个SqlCommand实例
SqlCacheDependencydep2 = new SqlCacheDependency(cmd);
//添加到CacheDependency对象组中
CacheDependency[]deps= new CacheDependency[]{ dep1, dep2 };
//调用Add方法,实现聚合缓存依赖
AggregateCacheDependencyaggDep= new AggregateCacheDependency();
aggDep.Add(deps);
//利用Insert方法,添加应用程序缓存对象
Cache.Insert(“key”,DateTime.Now,aggDep);