与业务逻辑层Employee对象的GetEmployeeById()方法相比,增加了缓存机制。当缓存内不存在相关数据项时,则直接调用业务逻辑层Employee的GetEmployeeById()方法来获取数据,并将其与对应的AggregateCacheDependency对象一起存储在缓存中。
//前台
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UseCache.aspx.cs" Inherits="WebApplicationUI.缓存的使用.UseCache" %>
<!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>
     
<asp:Button ID="btnSetCache" runat="server" Text="设置缓存"
οnclick="btnSetCache_Click" />
     
<asp:Button ID="btnReadCache" runat="server" Text="读取缓存"
οnclick="btnReadCache_Click" />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/TestWebForm.aspx">页面跳转</asp:HyperLink>
</div>
</form>
</body>
</html>
//后台
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 WebApplicationUI.缓存的使用
{
public partial class UseCache : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["age"] = "567";
this.Page.Title = getValue("123");
//this.Page.Title = getViewValue("test");
}
}
//设置缓存
protected void btnSetCache_Click(object sender, EventArgs e)
{
Cache["First"] = "First Item";
}
//读取缓存
protected void btnReadCache_Click(object sender, EventArgs e)
{
string str=(string) HttpRuntime.Cache["First"];
if (string.IsNullOrEmpty(str))//如果缓存为null的话
{
Response.Write("123");
}
else
{
Response.Write(Cache["First"]);
}
}
/// <summary>
/// 设计一个方法,如果字段在缓存中就返回字段,如果不在缓存中就显示123
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string getValue(string str)
{
string name = (string)HttpRuntime.Cache["name"];
if (!string.IsNullOrEmpty(name))
{
return name;
}
else
{
//AggregateCacheDependency cd = DependencyFacade.GetCategoryDependency();
AggregateCacheDependency cd = new AggregateCacheDependency();
//存储输出的数据缓存,并添加必要的AggregateCacheDependency对象
//HttpRuntime.Cache.Add(cacheKey, data, cd, DateTime.Now.AddHours(cacheDuration), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
HttpRuntime.Cache.Add("name", "good", cd, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
//HttpRuntime.Cache["name"] = str;
return "null";
}
}
private string getViewValue(string str)
{
string age = ViewState["age"].ToString();
if (!string.IsNullOrEmpty(age))
{
return str;
}
else
{
ViewState["age"] = "168";
return "null";
}
}
}
}