ASP.NET 1.x 快取機制僅支援絕對過期、滑動過期或檔案相依性。資料庫資料異動時,快取無法即時感知,必須等待過期才會重新載入,導致使用者看到髒資料。ASP.NET 2.0 引入 SqlCacheDependency,針對 SQL Server 7/2000/2005 實現「資料庫變更 → 快取自動失效」的即時同步機制。
aspnet_regsql.exe 啟用資料庫/資料表的通知機制。aspnet_SqlCacheTablesForChangeNotification 系統表,記錄受監控資料表與變更版本號。rem 1. 啟用資料庫層級通知
aspnet_regsql -S localhost -U sa -P 123456 -d Pubs -ed
rem 2. 啟用特定資料表通知
aspnet_regsql -S localhost -U sa -P 123456 -d Pubs -t authors -et
rem 3. 查看目前已啟用通知的資料表
aspnet_regsql -S localhost -U sa -P 123456 -d Pubs -lt
| 參數 | 說明 |
|---|---|
| -S | SQL Server 執行個體名稱或 IP |
| -U / -P | SQL 驗證帳號/密碼 |
| -E | 使用 Windows 整合驗證 (替代 -U/-P) |
| -d | 目標資料庫名稱 |
| -t | 目標資料表名稱 |
| -ed | 啟用資料庫通知 |
| -dd | 停用資料庫通知 |
| -et | 啟用資料表通知 |
| -dt | 停用資料表通知 |
| -lt | 列出已啟用通知的資料表 |
<configuration>
<connectionStrings>
<add name="PubsConn" connectionString="Server=localhost;Database=Pubs;Uid=sa;Pwd=123456;" />
</connectionStrings>
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="5000">
<databases>
<add name="Pubs" connectionStringName="PubsConn" />
</databases>
</sqlCacheDependency>
</caching>
</system.web>
</configuration>
pollTime:輪詢間隔 (毫秒),預設 5000ms (5 秒),依業務即時性需求調整。databases 區段可註冊多個資料庫連線。<%@ OutputCache Duration="3600" VaryByParam="none" SqlDependency="Pubs:authors" %>
Imports System.Web.Caching
Partial Class AuthorsPage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dep As New SqlCacheDependency("Pubs", "authors")
' 或使用連線字串名稱: New SqlCacheDependency("PubsConn", "authors")
Response.AddCacheDependency(dep)
Response.Cache.SetExpires(DateTime.Now.AddHours(1))
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("PubsConn").ConnectionString)
Dim cmd As New SqlCommand("SELECT * FROM authors", conn)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Sub
End Class
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" EnableCaching="true" CacheDuration="3600" />
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="AuthorsBLL" SelectMethod="GetAuthors"
SqlCacheDependency="Pubs:authors" />
EnableCaching="true" 且設定 SqlCacheDependency,GridView 會自動處理快取存取與相依性驗證。
aspnet_regsql 的帳號需具備 db_ddladmin、db_datawriter 權限以建立觸發器與系統表。SqlDependency (Query Notification) 推播模式,無需輪詢,延遲更低,但需啟用 Service Broker。SqlCacheDependency 解決了 ASP.NET 1.x 快取無法感知資料庫變更的長期痛點,透過簡單的設定即可實現「資料異動即時失效快取」,大幅提升資料呈現的正確性與系統回應速度。搭配 OutputCache、ObjectDataSource 等內建機制,開發者能以最少程式碼構建高效能、資料一致的 Web 應用。