Cache用法之頁面聲明
<%@ outputCache
Duration="#ofseconds"
Location="Any|Client|Downstream|Server|None"
VaryByControl="ControlName"
VaryByCustom="browser|customstring"
VaryByHeader="headers"
VaryByParam="Parametername" %>
Cache用法之代碼控制
HttpCachePolicy類是專門用來控制項Cache的,可以用Response.Cahce來訪問這個類的執行個體
Response.Cache.SetExpires(DateTime.Now.AddSeceonds(10));
Response.Cache.SetCacheability(HttpCacheablility.Public);
Response.Cache.SetValidUnitlExpires(true);
-----------------------以上都是快取頁面面的,下面是快取資料的----------------------------
Cache類的生存周期等於應用程式的生命週期
三種用法
1:存:Cache["key"] = MyData;取:
MyData = Cache["key"];
if(MyData != null)
use(MyData);
此法存入Cache的資料生命週期等於應用程式生命週期,不支援清除、到期、依賴性等功能。
2:存:
Cache.Insert(
string key,
object value,
CacheDependency dependencies,//依賴,設定緩衝有效依賴性,比如設定和一個檔案相關,檔案一變,就失效
DateTime absoluteExpireation, //設定固定的到期時間
TimeSpan slidingExpiration, //設定最後一次訪問後多長時間到期
CachePriority priority, //設定記憶體不足,緩衝自動清除時,緩衝的重要性,可不可以清除
CacheItemRemovedCallback onRemoveCallback // 設定在清除時引發的事件
)
Example:
Cache.Insert("Mydata",MyData,new Caching.CacheDependency(Server.MapPah("Mydata.XML")));//設定有效性和一個檔案有關
Cache.Insert("Mydata",myData,null,DateTime.Now.AddDays(1),Cache.NoSlidingExpiratin);//兩種到期時間設了其中一種,另一種要設為0,用NoAbsolute(Sliding)Expiration枚舉
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10));//不能過一年不能小於0
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10),
Caching.CacheItemPriority.NotRemovable,null);
// AboveNormal|BelowNormal|Default|High|Low|Normal|NotRemovable
public void RemovedCallback(string key,object value,CacheItemRemovedReason reason)
{
if(reason == CacheItemRemovedReason.DependencyChanged)
Response.Write("檔案變了,快去看看");
}
Cache.Insert("Mydata",MyData,new Caching.CacheDependency(Server.MapPah("Mydata.XML"),
DateTime.Now.AddDays(1),Cache.NoSlidingExpiration,CacheItemPriority.High,
new CacheItemRemovedCallback(this.RemovedCallback));
清除就可以用Cache.Remove("key");方法
3:
Cache.Add方法,用法和Insert差不多,區別在於Add碰到該key原來有賦過值會失敗,Insert則不會,而會替換原有值;Add會返回被快取資料項,Insert不會
文章來自: 鴻石網際(http://www.hungstone.cn/)