Code
在訪問量非常大,但更新較少的網站中使用緩衝,可以大大提高程式啟動並執行效率,給網路使用者一個良好的體驗效果。在Microsoft提供的經典樣本項目.Net PetShop 4.0中,也提供了對緩衝的支援,本文是作者在學習此項目時的一些心得體會,有一些地方還不十分清楚,希望能夠拋磚引玉。
在.Net PetShop 4.0中,非常成功地使用了原廠模式以及介面(interface)、靜態類(Static class)、抽象類別(abstract class)等成員。在使用緩衝時,也是通過web.config配置進行設定,在使用時非常靈活。下面從底向上具體分析.Net PetShop 4.0緩衝方面的技術。
首先看一下該項目中與緩衝直接相關的命名空間:
PetShop.ICacheDependency
PetShop.TableCacheDependency
PetShop.CacheDependencyFactory
PetShop.Web
一、PetShop.ICacheDependency命名空間
最低層應該是介面的定義了,在PetShop.ICacheDependency命名空間中只定義了一個介面IPetShopCacheDependency,該介面只有一個方法 GetDependency,沒有任何參數,返回AggregateCacheDependency類型。AggregateCacheDependency是在.NET Framework 2.0 版中是新增的類,組合 ASP.NET 應用程式的 Cache 對象中儲存的項和 CacheDependency 對象的數組之間的多個依賴項(MSDN中原話)。
二、PetShop.TableCacheDependency命名空間
在PetShop.TableCacheDependency命名空間中,提供兩種類:抽象類別TableDependency和它的繼承類Category、Item和Product。抽象類別TableDependency的建構函式為:
protected TableDependency(string configKey) {
string dbName = ConfigurationManager.AppSettings["CacheDatabaseName"];
string tableConfig = ConfigurationManager.AppSettings[configKey];
string[] tables = tableConfig.Split(configurationSeparator);
foreach (string tableName in tables)
dependency.Add(new SqlCacheDependency(dbName, tableName));
}
傳遞了一個參數configKey,根據該參數從web.config檔案中擷取表名列表,同時在web.config中擷取資料庫名稱。將表名列表中的所有資料表添加到AggregateCacheDependency類型的dependency變數中。在此外使用了.NET Framework 2.0 版中是新增的另一個與緩衝有關的SqlCacheDependency類。這個類用於建立ASP.NET應用程式的Cache對象中儲存的項和特定SQL Server資料庫表之間的聯絡。AggregateCacheDependency和SqlCacheDependency都從CacheDependency繼承而來,但在.NET 2.0中還未提供Oracle等其它資料庫對應的類。
下面是web.config檔案中與緩衝相關的設定:
<!-- Cache dependency options. Possible values: PetShop.TableCacheDependency for SQL Server and keep empty for ORACLE -->
<add key="CacheDependencyAssembly" value="PetShop.TableCacheDependency"/>
<!-- CacheDatabaseName should match the name under caching section, when using TableCacheDependency -->
<add key="CacheDatabaseName" value="MSPetShop4"/>
<!-- *TableDependency lists table dependency for each instance separated by comma -->
<add key="CategoryTableDependency" value="Category"/>
<add key="ProductTableDependency" value="Product,Category"/>
<add key="ItemTableDependency" value="Product,Category,Item"/>
每個繼承類都只有一個建構函式,通過設定基類的configKey參數變成了三個不同的類。Product類的建構函式為:
public Product() : base("ProductTableDependency") { }
三、PetShop.CacheDependencyFactory命名空間
在PetShop.CacheDependencyFactory命名空間中有兩個類,分別是DependencyAccess和DependencyFacade。如果瞭解微軟以前提供的一些經典例子的分層,便不難理解這兩個類的命名以及它們對應的層次層級。這兩個類都是靜態類,DependencyAccess類裡面的方法都是返回IPetShopCacheDependency,而DependencyFacade裡面的方法都是返回AggregateCacheDependency。
DependencyAccess類裡面關鍵的一個方法是LoadInstance,它是原廠模式的具體實現。其代碼如下:
private static IPetShopCacheDependency LoadInstance(string className) {
string path = ConfigurationManager.AppSettings["CacheDependencyAssembly"];
string fullyQualifiedClass = path + "." + className;
// Using the evidence given in the config file load the appropriate assembly and class
return (IPetShopCacheDependency)Assembly.Load(path).CreateInstance(fullyQualifiedClass);
}
在這個方法中通過設定檔中的設定和傳進來的參數className,返回相對應的程式集和類。DependencyAccess類裡面的其它三個方法,只是調用這個方法,傳入不同的參數而已。
DependencyFacade類提供的三個方法正好與DependencyAccess類的三個方法相對應,分別擷取Category、Item和Product的AggregateCacheDependency。在DependencyFacade類中還讀取了web.config中的CacheDependencyAssembly設定,從而決定是調用DependencyAccess對應的方法,還是直接返回null。
四、PetShop.Web命名空間
在PetShop.Web的App_Code中,有四個靜態類與緩衝直接相關,分別是CategoryDataProxy、ItemDataProxy、ProductDataProxy和WebUtility。其中前三個分別調用DependencyFacade對應的方法,遺憾的是在哪裡(或者說如何)使用這三個類我還沒有完全弄清楚。
WebUtility中有兩個方法GetCategoryName和GetProductName使用了緩衝,下面是GetCategoryName的部分代碼:
if (data == null) {
// Caching duration from Web.config
int cacheDuration = int.Parse(ConfigurationManager.AppSettings["CategoryCacheDuration"]);
// If the data is not in the cache then fetch the data from the business logic tier
data = category.GetCategory(categoryId).Name;
// Create a AggregateCacheDependency object from the factory
AggregateCacheDependency cd = DependencyFacade.GetCategoryDependency();
// Store the output in the data cache, and Add the necessary AggregateCacheDependency object
HttpRuntime.Cache.Add(cacheKey, data, cd, DateTime.Now.AddHours(cacheDuration), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
在.Net 2.0中,對緩衝的維護有兩種方式:第一種是每次使用緩衝之間進行判斷緩衝是否存,如果不存在則讀取資料存入緩衝;另外一種方式是使用CacheItemRemovedCallback委託來實現,當緩衝失效時自動調用委託過程,重新產生緩衝。從上面的代碼來看,.Net PetShop 4.0使用的是第一種方式。