缓存是个啥?以及为啥要用缓存就不废话了,主要是从实用角度讲下怎么用
1.先添加对Microsoft.Practices.EnterpriseLibrary.Caching.dll的引用
2.修改web.config文件,注意高度部分
<configSections>
...
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral" />
...
</configSections>
<cachingConfiguration defaultCacheManager="Cache Manager">
<cacheManagers>
<add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000"
numberToRemoveWhenScavenging="10" backingStoreName="Null Storage"
type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral"
name="Cache Manager" />
</cacheManagers>
<backingStores>
<add encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral"
name="Null Storage" />
</backingStores>
</cachingConfiguration>
...
3.使用缓存,见下面的代码,关键地方都加了注释
using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
namespace CacheTest
{
/// <summary>
/// 定义要缓存的实体类
/// </summary>
public class MyData
{
public string Name { set; get; }
public int Age { set; get; }
public string Color { set; get; }
}
public partial class _Default : System.Web.UI.Page
{
const string KEYNAME = "myDate";//缓存的键值
ICacheManager cacheManager;
protected void Page_Load(object sender, EventArgs e)
{
cacheManager = CacheFactory.GetCacheManager();//实例化ICachemanager
}
protected void btnWrite_Click(object sender, EventArgs e)
{
//生成要缓存的数据(实际开发中可以是从数据库查询出来的数据)
List<MyData> _list = new List<MyData>{
new MyData(){ Age=1, Color="Yellow", Name="China"},
new MyData{ Age=2,Color="Black",Name="USA"}
};
AbsoluteTime _ExpireTime = new AbsoluteTime(DateTime.Now.AddSeconds(30));//指定30秒后过期
cacheManager.Add(KEYNAME, _list, CacheItemPriority.Normal, null, _ExpireTime);//加入缓存
Response.Write("Cache写入完成," + DateTime.Now.ToString());
}
protected void btnRead_Click(object sender, EventArgs e)
{
this.R1.DataSource = GetCacheData();
this.R1.DataBind();
Response.Write("Cache加载完成," + DateTime.Now.ToString());
}
/// <summary>
/// 获取缓存数据
/// </summary>
/// <returns></returns>
public List<MyData> GetCacheData()
{
List<MyData> _cacheData = cacheManager.GetData(KEYNAME) as List<MyData>;
if (null == _cacheData)//记得一定要加此判断(因为缓存可能过期)
{
//如果缓存数据为空,则重新生成数据,并加入缓存(为检测效果,特地把Color与Name前加了一个"New")
_cacheData = new List<MyData>{
new MyData(){ Age=1, Color="New Yellow", Name="New China"},
new MyData{ Age=2,Color="New Black",Name="New USA"}
};
AbsoluteTime _ExpireTime = new AbsoluteTime(DateTime.Now.AddSeconds(30));//指定30秒后过期
cacheManager.Add(KEYNAME, _cacheData, CacheItemPriority.Normal, null, _ExpireTime);
}
return _cacheData;
}
}
}
前端页面很简单
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CacheTest._Default" %>
<!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">
<asp:Button ID="btnWrite" runat="server" Text="Write Cache" OnClick="btnWrite_Click" />
<asp:Button ID="btnRead" runat="server" Text="Load Cache"
onclick="btnRead_Click" />
<asp:Repeater ID="R1" runat="server" EnableViewState="false">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>Age:<%# Eval("Age") %>,Name:<%# Eval("Name")%>,Color:<%# Eval("Color")%></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
值得一提的是,缓存是"全局"性质的,也就是说在一个页面写入了缓存,另一个页面也可以读取(当然:前提是缓存未过期的情况下),我们可以利用这个特性把网站中经常使用的数据(比如一些基础数据)缓存起来,其它要用的地方直接从缓存读取,能有效减少对数据库的访问。