.Net Cache及(HttpRuntime.Cache與HttpContext.Current.Cache的區別)

來源:互聯網
上載者:User

標籤:out   開始   生命週期   minutes   exp   order   exec   glob   net   

因為程式中用到 在當前會話上下文中緩衝多個資料庫的需求,所有查了下資料。

我們在.NET運用中經常用到緩衝(Cache)對象。
除了System.Web.Caching下的Cache外,我們還可以用到HttpContext.Current.Cache以及HttpRuntime.Cache
那麼,HttpContext.Current.Cache以及HttpRuntime.Cache有什麼區別呢?
從MSDN上的解釋可以看出,HttpRuntime.Cache是應用程式層級的,而HttpContext.Current.Cache是針對當前WEB上下文定義的。
然而,實際上,這二個都是調用的同一個對象,不同的是:HttpRuntime下的除了WEB中可以使用外,非WEB程式也可以使用。
而HttpContext則只能用在WEB中。

因此,在可能的情況下,我們儘可能使用HttpRuntime(然而,在不同應用程式之間如何調用也是一個問題)。


了更快的讀取資料,我們一般會把常用到的資料載入到Cache中 在.NET中,Cache的存在可以依賴多中方式,主要用到HttpContext.Current.Cache類 在這裡,我主要寫幾種依賴方式 1:不依賴任何條件 HttpContext.Current.Cache.Insert(string cacheName,object obj) 理論上是Cache會永久儲存,但是當伺服器重新啟動,記憶體緊張的時候也會丟失. 2:HttpContext.Current.Cache.Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration); //CacheDependency緩衝依賴項,absoluteExpiration絕對到期時間,slidingExpiration最後一次訪問的時間隔 //我們主要講兩種Cache依賴 2.1:檔案依賴,so simple//只要檔案改動,Cache移出 HttpContext.Current.Cache.Insert(cacheName,ojb, new System.Web.Caching.CacheDependency(FilePath)); 2.2:SqlServer資料庫依賴//我這裡是SQL2005 首先看資料庫通知是否可用,記得一定要開啟通知 Select DATABASEpRoPERTYEX(‘資料庫名‘,‘IsBrokerEnabled‘);如果值為1表示可用 alter database Game176Admin set ENABLE_BROKER ;//開啟alter database Game176Admin set DISABLE_BROKER;//關閉 在Global.asax檔案中,我們在應用程式開始和結束時要做一些事情 void Application_Start(object sender, EventArgs e){// 在應用程式啟動時啟動並執行代碼try{System.Data.SqlClient.SqlDependency.Start(string strCon);//開啟}catch { }} void Application_End(object sender, EventArgs e){// 在應用程式關閉時啟動並執行代碼try{System.Data.SqlClient.SqlDependency.Stop(string strCon);}catch { }} 準備工作已經完成 我們先寫一個方法,添加資料庫依賴 void AddSqlDependency(string strCon, string strSql, OnChangeEventHandler sqlDep_OnChange){try{using (SqlConnection conn = new SqlConnection(strCon)){SqlCommand comm = new SqlCommand(strSql, conn);SqlDependency sqlDep = new SqlDependency(comm);sqlDep.OnChange += sqlDep_OnChange;if (conn.State == ConnectionState.Closed) conn.Open();comm.ExecuteNonQuery();}}catch (Exception ex){LogUtility.Add(ex);}} //上面這個方法是告訴資料庫,當你指定表資料改變,要移出緩衝 我們現在可以來添加了 MyObject obj= HttpRuntime.Cache["cacheName"] as MyObject;if (null == obj){try{obj= GetObj(...);}catch (Exception ex){LogUtility.Add(ex);obj= null;}if (null != obj){AddSqlDependency(strCon, "select id from dbo.tableName;select id1 from dbo.tableName1",delegate(object sender, SqlNotificationEventArgs e){//do something HttpRuntime.Cache.Remove("cacheName");});HttpRuntime.Cache.Insert("cacheName", obj);}} 上面SQL語句中用到的表,只要這些表中的任何資料有改動,資料庫都會通知,這時緩衝會移動,select的欄位和Cache沒有關係,只有表名有關係,所有你要選擇最小的欄位.很多時候,為了這個欄位,在設計表的時候都為多加一個最小的依賴列. NOTE:任何Cache都可能丟失,使用前一定要做必要的檢查,如: MyObject obj=HttpContext.Current.Cache("CacheName") as MyObject; if(null==obj) { obj=....... HttpContext.Current.Cache.Insert("CacheName",obj); }Cache用法之頁面聲明 <%@ outputCacheDuration="#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));//不能過一年不能小於0Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10),Caching.CacheItemPriority.NotRemovable,null);// AboveNormal|BelowNormal|Default|High|Low|Normal|NotRemovablepublic 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不會

.Net Cache及(HttpRuntime.Cache與HttpContext.Current.Cache的區別)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.