这种策略让缓存依赖于一个指定的文件,经过改变文件的更新日期来清除缓存。缓存
///<summary>服务器 ///获取当前应用程序指定CacheKey的Cache对象值负载均衡 ///</summary>spa ///<param name="CacheKey">索引键值</param>对象 ///<returns>返回缓存对象</returns>索引 public staticobject GetCache(string CacheKey)ci {同步 System.Web.Caching.Cache objCache =HttpRuntime.Cache;string return objCache[CacheKey];it } ///<summary> ///设置以缓存依赖的方式缓存数据 ///</summary> ///<param name="CacheKey">索引键值</param> ///<param name="objObject">缓存对象</param> ///<param name="cacheDepen">依赖对象</param> public staticvoid 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应用中的缓存依赖于同一个共享的文件,可能会省掉这个麻烦。