ASP.NET狀態儲存管理九大兵器之六(緩衝)- -

來源:互聯網
上載者:User

ASP.NET 提供一個功能完整的緩衝引擎,頁面可使用該引擎通過 HTTP 要求儲存和檢索任意對象.
緩衝的生存期與應用程式的生存期相同,也就是說,當應用程式重新啟動時,將重新建立緩衝。

將資料添加到緩衝中

1。通過指定其鍵和值將項添加到緩衝中
Cache["txt"] = "a";

2.通過使用 Insert(重載Insert方法)方法將項添加到緩衝中

Cache.Insert("txt", "a");

下列代碼顯示如何設定相對到期策略。它插入一個項,該項自上次訪問後 10 分鐘到期。注意

DateTime.MaxValue 的使用,它表示此項沒有絕對到期策略。

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Cache.Insert("txt", "a",null,
absoluteExpiration,slidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

3.使用 Add 方法將項添加到緩衝中
Add 方法與 Insert 方法具有相同的簽名,但它返回表示您所添加項的對象

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Object  Ojb=(string)Cache.Add("txt","a",null,
absoluteExpiration ,slidingExpiration ,
System.Web.Caching.CacheItemPriority.High,null);
string str=(string)Ojb ;
Response.Write(str);

結果顯示是"a"

Add 方法使用上沒有Insert 方法靈活,使用Add 方法時必須提供7個參數,Insert 方法重載4次,我們可

以根據需要選擇適當重載方法

從緩衝中取得資料

方式1:
string str=(string)Cache.Get("txt");
Response.Write(str);

方式2:
string str1=(string)Cache["txt1"];
Response.Write(str1);

查看Cache中所有資料

System.Text.StringBuilder sb=new System.Text.StringBuilder("",100);
foreach(DictionaryEntry Caches  in Cache)
{
sb.Append("key=").Append(Caches.Key.ToString()).Append("<br>") ;
sb.Append("value=").Append(Caches.Value.ToString()).Append("<br>");
}
Response.Write(sb.ToString());

查看Cache中的項數

int Count=Cache.Count;
Response.Write(Count.ToString());

將資料從緩衝中刪除

Cache.Remove("txt");

使Cache具有檔案依賴項或鍵依賴項的對象

我們在一頁面建立1個按鈕,查看CACHE是否存在
在表單啟動時我們建立CACHE,名稱="txt2",數值=資料集ds
該CACHE與myfile.xml相關聯,當myfile.xml檔案變化時,txt2CACHE就被自動刪除

private void Page_Load(object sender, System.EventArgs e)
  {
   if( !IsPostBack  )
   {
   string FilePath=MapPath("myfile.xml");
   SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
   SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
   DataSet ds=new DataSet();
   da.Fill(ds);
   System.Web.Caching.CacheDependency CacheDependencyXmlFile=new

System.Web.Caching.CacheDependency(FilePath);
   Cache.Insert("txt2",ds ,CacheDependencyXmlFile);
   }
  }

為了監視pubs資料庫authors表的變化
我們可以在pubs資料庫authors表建立觸發器
一旦authors表中發生增加,刪除,修改資料時,觸發器會自動修改檔案myfile.xml
一旦myfile.xml檔案變化,txt2CACHE就被系統自動刪除

CREATE TRIGGER tr_authors
ON authors
FOR INSERT, UPDATE ,delete
AS
declare @cmd nvarchar(4000)
select @cmd='bcp "select convert(nvarchar(30),Getdate(),13)" queryout

D:\cache\WebCache\myfile.xml -c -Sglc2403 -Usa -P'
exec master..xp_cmdshell @cmd
GO

private void QueryButton_Click(object sender, System.EventArgs e)
{
if ( Cache["txt2"]!=null)
{
 Response.Write("exists");
}
else
{
 Response.Write("not exists");
}
}

首先我們點按鈕,顯示Cache["txt2"]存在
現在我們去表authors中任意修改一資料,再點按鈕,顯示Cache["txt2"]不存在拉

以上我們是把CACHE是和一個檔案相關聯,我們還可以把CACHE和檔案組關聯,建立依賴
以下我們把CACHE和2個檔案(myfile.xml,myfile1.xml)關聯,一旦檔案組中其中任意一檔案變化,Cac

he會把"txt2"項的資料從CACHE中刪除

string[] FilePath=new String[]{MapPath("myfile.xml"),MapPath("myfile1.xml")};
System.Web.Caching.CacheDependency CacheDependencyXmlFile=new                    

System.Web.Caching.CacheDependency(FilePath);
string CacheVaule="a";
Cache.Insert("txt2", CacheVaule ,CacheDependencyXmlFile);

 

緩衝依賴可以是檔案,還可以是其他對象的鍵
下面的代碼說明緩衝Cache["txt2"]既依賴檔案myfile.xml,又依賴緩衝中的Cache["txt"],只要這2者任

意一樣改變,緩衝Cache["txt2"]就會清除

Cache["txt"] = "b";
string[] FilePath=new String[]{ MapPath("myfile.xml")};
string[] dependencyKey=new String[]{"txt"};
SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
DataSet ds=new DataSet();
da.Fill(ds);
System.Web.Caching.CacheDependency CacheDependencyXmlFile=
          new System.Web.Caching.CacheDependency(FilePath,dependencyKey);
Cache.Insert("txt2",ds ,CacheDependencyXmlFile);

緩衝絕對到期

緩衝Cache["txt3"] 在1小時後自動到期
DateTime absoluteExpiration =DateTime.Now.AddHours(1);
Cache.Insert("txt3","aa",null,absoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiratio

n);

緩衝相對(滑動)到期

注意:如果建立的彈性到期時間小於零或大於一年,則將引發異常
緩衝Cache["txt4"] 在最後一次被訪問後1小時自動到期
TimeSpan slidingExpiration=TimeSpan.FromHours(1);
Cache.Insert("txt4","4",null,System.Web.Caching.Cache.NoAbsoluteExpiration,slidingExpiration

);

快取項目的優先等級

當承載 ASP.NET 應用程式的 Web 服務器缺少記憶體時,Cache 將有選擇地清除項來釋放系統記憶體。當向緩

存添加項時,可以為其分配與緩衝中儲存的其他項相比較的相對優先順序。在伺服器處理大量請求時,分配

了較高優先順序值的項被從緩衝刪除的可能性較小,而分配了較低優先順序值的項則更有可能被刪除。
由CacheItemPriority 枚舉表示,預設為 Normal。

緩衝Cache["txt5"]優先等級設為最高等級,在伺服器釋放系統記憶體時,該快取項目最不可能被刪除。
Cache.Insert("txt5","5",null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

快取項目時通知應用程式的回調方法

ASP.NET 提供 CacheItemRemovedCallback 委託。它定義編寫事件處理常式時使用的簽名,當從緩衝中刪

除項時,該事件處理常式將進行響應。

static System.Web.Caching.CacheItemRemovedReason reason;
System.Web.Caching.CacheItemRemovedCallback onRemove = null;

public void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
{
 itemRemoved = true;
 reason = r;
}

onRemove = new System.Web.Caching.CacheItemRemovedCallback (this.RemovedCallback);
Cache.Insert("txt",ds,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,onRemove);

 

由於任何原因從Cache中移除時,將調用 RemovedCallback 方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.