1. 程式人生 > >HttpContext.Current.Cache 過期時間

HttpContext.Current.Cache 過期時間

dds ceo close logutil 依賴項 rop exp ons valid

為了更快的讀取數據,我們一般會把常用到的數據加載到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用法之頁面聲明

<%@ 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不會

HttpContext.Current.Cache 過期時間