以petshop中的NavigationControl.ascx控件为例,以下的“页”即指“NavigationControl.ascx”控件
页中通过:
Code
<%@ OutputCache Duration="10" VaryByParam="*" %>
设置了页缓存,由于担心数据过期,所以设置了页的依赖项:
Code
this.CachePolicy.Dependency = DependencyFacade.GetCategoryDependency();
并采用轮询机制定期查看页的依赖项是否过期,如下:
Code
<caching>
<sqlCacheDependency enabled="true" pollTime="1000"><!--1秒=1000毫秒-->
<databases>
<add name="PetShop" connectionStringName="MsSqlConnString" pollTime="1000"/>
</databases>
</sqlCacheDependency>
</caching>
每隔pollTime的时间查看数据库,看看页的依赖项(表)是否有数据更新,如果有更新,那么缓存失效,重新查询数据。
至于配置文件中的:
Code
<add key="CategoryCacheDuration" value="12"/>
<add key="ProductCacheDuration" value="12"/>
<add key="ItemCacheDuration" value="12"/>
则是用于数据缓存的缓存过期时间。从以下方法中可以看出,
Code
/// <summary>
/// Method to retrieve and cache category name by its ID
/// </summary>
/// <param name="categoryId">Category id</param>
/// <returns>Category name</returns>
public static string GetCategoryName(string categoryId) {
Category category = new Category();
if (!enableCaching)
return category.GetCategory(categoryId).Name;
string cacheKey = string.Format(CATEGORY_NAME_KEY, categoryId);
// Check if the data exists in the data cache
string data = (string)HttpRuntime.Cache[cacheKey];//1
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);//2
}
return data;
}