在asp.net中使用SqlDependency緩存
1 首先要在給Test_01數據庫打開監聽
ALTER DATABASE Test_01 SET ENABLE_BROKER;
注:SELECT is_broker_enabled FROM sys.databases WHERE name = 'Test_01'
查詢是否開啟此監聽(0未開啟,1開啟)
2 必須在 Test_01 數據庫中的 QueryNotificationService 服務上向Guest用戶授予發送權限。方法如下,注意要區分大小寫
USE Test_01GRANT SEND ON SERVICE::[http://schemas.microsoft.com/SQL/Notifications/QueryNotificationService]TO Guest
3 在web.config添加以下節點
<connectionStrings><add name="conStr"connectionString="PassWord=123456;Persist Security Info=True;User ID=sa;Initial Catalog=Test_01;Data Source=JUN-PC"在<system.web> 節點中添加
<caching><sqlCacheDependency enabled="true" pollTime="1000"><databases><add name="Test_01" connectionStringName="conStr"/></databases></sqlCacheDependency></caching>4 在程序啟動的時候設置緩存表(設置一次即可)
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; // 在應用程序啟動時運行的代碼SqlDependency.Start(conStr);//啟動監聽服務,ps:只需啟動一次System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(conStr);//設置通知的數據庫連接,ps:只需設置一次System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(conStr, "tb_people");//設置通知的數據庫連接和表,ps:只需設置一次5 查詢中保存緩存
SqlConnection conn = new SqlConnection(connstr); SqlCommand cmd = new SqlCommand(" select * from tb_People ", conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(ds, "cache"); System.Web.Caching.SqlCacheDependency cd = new System.Web.Caching.SqlCacheDependency("Test_01", "tb_people");//建立關聯 Cache.Insert("cache", ds, cd);
新聞熱點
疑難解答