時間基礎快取無法保證資料最新。SQL Cache Dependency 讓快取在資料庫資料異動時自動失效。SQL Server 2005 Express 僅支援 Polling 機制 (完整版支援 Notification)。
AspNet_SqlCacheTablesForChangeNotification 表:tableName, notificationCreated, changeId。changeId。changeId,異動則移除對應快取項目。aspnet_regsql -S localhost\SQLExpress -E -d Northwind -ed
aspnet_regsql -S localhost\SQLExpress -E -d Northwind -et -t Products
<caching>
<sqlCacheDependency pollTime="5000"> <!-- 5 秒輪詢,開發環境建議較短 -->
<databases>
<add name="Northwind" connectionStringName="NorthwindConnectionString" />
</databases>
</sqlCacheDependency>
</caching>
// 表現層 ObjectDataSource
<asp:ObjectDataSource ... SqlCacheDependency="Northwind:Products" />
// 程式碼快取層
public static List<Product> GetProducts()
{
string cacheKey = "ProductsCache";
List<Product> products = HttpRuntime.Cache[cacheKey] as List<Product>;
if (products == null)
{
products = ProductsBLL.GetProducts();
SqlCacheDependency dep = new SqlCacheDependency("Northwind", "Products");
HttpRuntime.Cache.Insert(cacheKey, products, dep);
}
return products;
}
| 特性 | Notification (Query-based) | Polling (Table-based) |
|---|---|---|
| 支援版本 | SQL Server 2005 完整版 | SQL Server 7.0+ (含 Express) |
| 監控粒度 | 特定查詢結果集 | 整張資料表 |
| 基礎建設 | Service Broker、Queue | Change Notification Table + Trigger |
| 即時性 | 近即時推播 | 輪詢間隔延遲 (預設 60 秒) |
SQL Cache Dependency 實現「資料異動即快取失效」,最大化快取效益同時最小化髒讀視窗。Express 環境採用 Polling,配置簡單、相容性佳。