这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存。
///
<summary>
///
获取当前应用程序指定CacheKey的Cache对象值
///
</summary>
///
<param name="CacheKey">
索引键值
</param>
///
<returns>
返回缓存对象
</returns>
public
static
object
GetCache(
string
CacheKey)
{
System.Web.Caching.Cache objCache
=
HttpRuntime.Cache;
return
objCache[CacheKey];
}
///
<summary>
///
设置以缓存依赖的方式缓存数据
///
</summary>
///
<param name="CacheKey">
索引键值
</param>
///
<param name="objObject">
缓存对象
</param>
///
<param name="cacheDepen">
依赖对象
</param>
public
static
void
SetCache(
string
CacheKey,
object
objObject, System.Web.Caching.CacheDependency dep)
{
System.Web.Caching.Cache objCache
=
HttpRuntime.Cache;
objCache.Insert
(
CacheKey,
objObject,
dep,
System.Web.Caching.Cache.NoAbsoluteExpiration,
//
从不过期
System.Web.Caching.Cache.NoSlidingExpiration,
//
禁用可调过期
System.Web.Caching.CacheItemPriority.Default,
null
);
}
protected
void
Page_Load(
object
sender, EventArgs e)
{
string
CacheKey
=
"
cachetest
"
;
object
objModel
=
GetCache(CacheKey);
//
从缓存中获取
if
(objModel
==
null
)
//
缓存里没有
{
objModel
=
DateTime.Now;
//
把当前时间进行缓存
if
(objModel
!=
null
) {
//
依赖 C:\\test.txt 文件的变化来更新缓存
System.Web.Caching.CacheDependency dep
=
new
System.Web.Caching.CacheDependency(
"
C:\\test.txt
"
);
SetCache(CacheKey, objModel, dep);
//
写入缓存
}
}
Label1.Text
=
objModel.ToString();
}
当我们改变test.txt的内容时,缓存会自动更新。这种方式非常适合读取配置文件的缓存处理。如果配置文件不变化,就一直读取缓存的信息,一旦配置发生变化,自动更新同步缓存的数据。
这种方式的缺点是,如果缓存的数据比较多,相关的依赖文件比较松散,对管理这些依赖文件有一定的麻烦。对于负载均衡环境下,还需要同时更新多台Web服务器下的缓存文件,如果多个Web应用中的缓存依赖于同一个共享的文件,可能会省掉这个麻烦。