使用SqlDependency進行緩存

緩存是每個系統都必定涉及到的功能,一般的緩存有一個難題——什麼時候清除?如Asp.Net中的cache可以設置一個過期時間,但設置多久合適呢?長了浪費,短了就失去緩存的意義了。使用SqlDependency進行緩存則可以解決這個問題。

SqlDependency是.net2.0封裝的一個類型,當然要配合sql2005或以上版本才能使用。

SqlDependency類需要數據庫的ServiceBroker來支持,當數據庫中的數據發生變化時通知應用程序更新緩存,這纔是最有效的緩存方式。

 

步驟一:

sql數據庫必須開啓ServiceBroker服務,首先檢測是否已經啓用ServiceBroker,檢測方法:

 

Select DATABASEpRoPERTYEX('數據庫名稱','IsBrokerEnabled')

 

 

--1表示已經啓用0表示沒有啓用

 

步驟二:

如果ServiceBroker沒有啓用,使用下面語句啓用:

ALTER DATABASE <數據庫名稱> SET ENABLE_BROKER;

 

步驟三:

在實現基於服務的SQL數據緩存依賴過程中,需要顯式調用SqlDependency.Start來啓動接受依賴項更改通知的偵聽器。

 

SqlDependency.Start(connectionString);//推薦將這段代碼加到Global.asax的Application_Start方法中 SqlDependency.Stop(connectionString);//用於關閉,可加在Global.asax的Application_End方法中

 

步驟四:緩存實現

 使用sqldependency實現緩存的代碼:

 

public class CacheHelper { 

static Cache WebCache = HttpContext.Current.Cache;

static string DefaultConn = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

public static DataTable GetSystemParams() {

if (WebCache["SystemParam"] == null) {

string strSQL = "select uSystemParamID,ParamName,ParamValue,Description from dbo.DTS_SystemParam";

SqlDataAdapter da = new SqlDataAdapter(strSQL, DefaultConn);

SqlDependency dep = new SqlDependency(da.SelectCommand);

dep.OnChange += new OnChangeEventHandler(dep_OnChange);

DataTable tbl = new DataTable(); da.Fill(tbl);

WebCache["SystemParam"] = tbl;

return tbl;

}

else {

return (DataTable) WebCache["SystemParam"];

}

}

private static void dep_OnChange(object sender, SqlNotificationEventArgs e) {

WebCache.Remove("SystemParam");

}

}

 

注意:

使用 SqlDependency 訂閱查詢通知必須向SQL Server Service Broker提供製定規則的查詢語句,一般來講,必須是簡單的sql查詢語句(不能用*,不能用top,不能用函數,包括聚合函數,不能用子查詢,包括where後的子查詢,不能用外連接,自連接,不能用臨時表,不能用變量,不能用視圖,不能垮庫,表名之前必須加類似dbo數據庫所有者這樣的前綴例如:select * from table1,select column1 from table1,select count(*) from table1 都是錯誤的sql查詢語句,select column1 from dbo.table1 則是正確的語句。

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