在 Web 應用中,Cache 物件允許將資料保存在記憶體中,避免重複查詢資料庫。設定合理的失效策略至關重要,本文示範三種常見方式:檔案相依性、絕對過期時間、滑動過期時間。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CacheDemo.WebForm1" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cache 失效策略示範</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Cache["news"] == null)
{
DataTable dt = LoadData();
// 策略一:檔案相依性 —— 檔案異動即刻失效
// Cache.Insert("news", dt, new CacheDependency(@"d:\cache.txt"));
// 策略二:絕對過期時間 —— 固定時間點失效
// Cache.Insert("news", dt, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
// 策略三:滑動過期時間 —— 閒置超過指定時間失效(此處啟用)
Cache.Insert("news", dt, null, DateTime.MaxValue, TimeSpan.FromSeconds(30));
// 簡單快取(無失效策略,需手動移除)
// Cache.Insert("news", dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
else
{
DataTable dt = Cache["news"] as DataTable;
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
}
private DataTable LoadData()
{
string strcon = ConfigurationManager.ConnectionStrings["Sqlserver"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strcon))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "pro_FenYe";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@pagesize", 500);
cmd.Parameters.AddWithValue("@pageindex", 1);
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(dt);
}
return dt;
}
}
| 策略 | 適用場景 | 特點 |
|---|---|---|
| 檔案相依性 | 設定檔、外部資料檔變更需即時反映 | 檔案異動即觸發失效,即時性強 |
| 絕對過期 | 資料更新頻率固定、可預測的業務 | 到點必失效,簡單可控 |
| 滑動過期 | 熱門資料、讀取頻率不固定 | 持續被存取則延長壽命,節省記憶體 |
<system.web>
<compilation debug="true" targetFramework="4.0" />
<caching>
<sqlCacheDependency pollTime="500">
<databases>
<add name="sqldependency" connectionStringName="Sqlserver" />
</databases>
</sqlCacheDependency>
</caching>
</system.web>
pollTime 為輪詢間隔(毫秒),需搭配 aspnet_regsql 啟用資料庫查詢通知。