緩存是個啥?以及為啥要用緩存就不廢話了,主要是從實用角度講下怎麼用
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>
值得一提的是,緩存是"全局"性質的,也就是說在一個頁面寫入了緩存,另一個頁面也可以讀取(當然:前提是緩存未過期的情況下),我們可以利用這個特性把網站中經常使用的資料(比如一些基礎資料)緩存起來,其它要用的地方直接從緩存讀取,能有效減少對資料庫的通路。