首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 資料教程 61:SQL Cache Dependency 實作-Polling 機制、資料庫基礎建設、SqlCacheDependency 類別使用與快取失效策略

     編輯:關於ASP.NET

前言

時間基礎快取無法保證資料最新。SQL Cache Dependency 讓快取在資料庫資料異動時自動失效。SQL Server 2005 Express 僅支援 Polling 機制 (完整版支援 Notification)。

Polling 機制運作原理

  1. 資料庫建立 AspNet_SqlCacheTablesForChangeNotification 表:tableName, notificationCreated, changeId。
  2. 每個受監控資料表建立 Trigger:INSERT/UPDATE/DELETE 時遞增 changeId。
  3. ASP.NET 定期輪詢 (預設 60 秒) 比對 changeId,異動則移除對應快取項目。

基礎建設啟用步驟

1. 啟用資料庫 Polling 支援

aspnet_regsql -S localhost\SQLExpress -E -d Northwind -ed

2. 啟用資料表監控

aspnet_regsql -S localhost\SQLExpress -E -d Northwind -et -t Products

3. Web.config 設定輪詢間隔與連接字串

<caching>
  <sqlCacheDependency pollTime="5000"> <!-- 5 秒輪詢,開發環境建議較短 -->
    <databases>
      <add name="Northwind" connectionStringName="NorthwindConnectionString" />
    </databases>
  </sqlCacheDependency>
</caching>

程式碼使用 SqlCacheDependency

// 表現層 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 vs Polling 比較

特性Notification (Query-based)Polling (Table-based)
支援版本SQL Server 2005 完整版SQL Server 7.0+ (含 Express)
監控粒度特定查詢結果集整張資料表
基礎建設Service Broker、QueueChange Notification Table + Trigger
即時性近即時推播輪詢間隔延遲 (預設 60 秒)

結語

SQL Cache Dependency 實現「資料異動即快取失效」,最大化快取效益同時最小化髒讀視窗。Express 環境採用 Polling,配置簡單、相容性佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved