ASP.NET缓存全解析5:文件缓存依赖(转)
ASP.NET缓存全解析文章索引
- ASP.NET缓存全解析1:缓存的概述
- ASP.NET缓存全解析2:页面输出缓存
- ASP.NET缓存全解析3:页面局部缓存
- ASP.NET缓存全解析4:应用程序数据缓存
- ASP.NET 缓存全解析5:文件缓存依赖
- ASP.NET 缓存全解析6:数据库缓存依赖
- ASP.NET 缓存全解析7:第三方分布式缓存解决方案 Memcached和Cacheman
这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存。
///<summary>
/// 获取当前应用程序指定CacheKey的Cache对象值
///</summary>
///<param name="CacheKey">索引键值</param>
///<returns>返回缓存对象</returns>
publicstaticobject 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>
publicstaticvoid 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);
}
protectedvoid 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();
}
/// 获取当前应用程序指定CacheKey的Cache对象值
///</summary>
///<param name="CacheKey">索引键值</param>
///<returns>返回缓存对象</returns>
publicstaticobject 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>
publicstaticvoid 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);
}
protectedvoid 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();
}
这种方式的缺点是,如果缓存的数据比较多,相关的依赖文件比较松散,对管理这些依赖文件有一定的麻烦。对于负载均衡环境下,还需要同时更新多台Web服务器下的缓存文件,如果多个Web应用中的缓存依赖于同一个共享的文件,可能会省掉这个麻烦。
浙公网安备 33010602011771号