C#中Cache的使用

公共方法
Add 將指定項添加到 Cache 對象,該對象具有依賴項、過期和優先級策略以及一個委託(可用於在從 Cache 移除插入項時通知應用程序)。
Equals(從 Object 繼承) 已重載。確定兩個 Object 實例是否相等。
Get 從 Cache 對象檢索指定項。
GetEnumerator 檢索用於循環訪問包含在緩存中的鍵設置及其值的字典枚舉數。
GetHashCode(從 Object 繼承) 用作特定類型的哈希函數,適合在哈希算法和數據結構(如哈希表)中使用。
GetType(從 Object 繼承) 獲取當前實例的 Type。
Insert 已重載。向 Cache 對象插入項。使用此方法的某一版本改寫具有相同 key 參數的現有 Cache 項。
Remove 從應用程序的 Cache 對象移除指定項。
ToString(從 Object 繼承) 返回表示當前 Object 的 String。


public object Add(
   string key,
   object value,
   CacheDependency dependencies,
   DateTime absoluteExpiration,
   TimeSpan slidingExpiration,
   CacheItemPriority priority,
   CacheItemRemovedCallback onRemoveCallback
);

參數
key
用於引用該項的緩存鍵。
value
要添加到緩存的項。
dependencies
該項的文件依賴項或緩存鍵依賴項。當任何依賴項更改時,該對象即無效,並從緩存中移除。如果沒有依賴項,則此參數包含空引用(Visual Basic 中爲 Nothing)。
absoluteExpiration
所添加對象將過期並被從緩存中移除的時間。
slidingExpiration
最後一次訪問所添加對象時和該對象過期時之間的時間間隔。如果該值等效於 20 分鐘,則對象在最後一次被訪問 20 分鐘之後將過期並從緩存中移除。
priority
對象的相對成本,由 CacheItemPriority 枚舉表示。緩存在退出對象時使用該值;具有較低成本的對象在具有較高成本的對象之前被從緩存移除。
onRemoveCallback
在從緩存中移除對象時所調用的委託(如果提供)。當從緩存中刪除應用程序的對象時,可使用它來通知應用程序。
示例
public void AddItemToCache(Object sender, EventArgs e) {
    itemRemoved = false;

    onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

    if (Cache["Key1"] == null)
      Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
}

將數據添加到緩存中

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("
") ;
sb.Append("value=").Append(Caches.Value.ToString()).Append("
");
}
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)關聯,一旦文件組中其中任意一文件變化,Cache會把"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.NoSlidingExpiration);

緩存相對(滑動)過期

注意:如果創建的彈性到期時間小於零或大於一年,則將引發異常
緩存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 方法
-

資料引用:http://www.knowsky.com/539463.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章