為ASP.NET應用程式啟用SQL緩衝

來源:互聯網
上載者:User

步驟一:

sql資料庫必須開啟ServiceBroker服務,首先檢測是否已經啟用ServiceBroker,檢測方法:

SELECT DATABASEPROPERTYEX('dbName','IsBrokerEnabled') --1表示已經啟用,0表示未啟用

如果是建立的新資料庫,預設是已啟用(1)。如果還原資料庫,預設是未啟用(0)。

步驟二:

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

ALTER DATABASE dbName SET ENABLE_BROKER;

此行此語句時有可能時間會很長,對此可以重啟SQL查詢編輯再執行以上語句。

步驟三:

如果使用的是SQL Server 2005/2008版本資料庫,只需在Page_Load或者Application_Start使用如下語句即可啟用ASP.NET對應的SQL緩衝:

SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

對於使用更低版本需要使用aspnet_regsql來配置。

另外,在最初時使用的是如下語句:

String[] tables = ConfigurationManager.AppSettings["CacheDataTable"].Split(',');SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString, tables);

在使用上面的語句始終報異常:沒有為 SQL 快取通知啟用資料庫(不知道為什麼)

步驟四:

通過以上步驟就可以編寫相應的緩衝代碼,代碼如下:

public class TableDependency{    protected char[] configurationSeparator = new char[] { ',' };    protected AggregateCacheDependency dependency = new AggregateCacheDependency();    protected TableDependency(string configKey)    {        string dbName = ConfigurationManager.AppSettings["CacheDatabaseName"];//要緩衝的資料庫名稱        string tableConfig = ConfigurationManager.AppSettings[configKey];//從設定檔中擷取需要緩衝的表,以','分隔        string[] tables = tableConfig.Split(configurationSeparator);        foreach (string tableName in tables)            dependency.Add(new SqlCacheDependency(dbName, tableName));//把表以及對應的資料庫添加到AggregateCacheDependency對象中    }    public AggregateCacheDependency GetDependency()    {        return dependency;    }}
String PHONE_HEAD_KEY="User_{0}";String cacheKey = String.Format(PHONE_HEAD_KEY, ID);//緩衝鍵String data = (String)HttpRuntime.Cache[cacheKey];//首先從緩衝來擷取相應的資料if (data == null){    //從資料庫擷取    data = db.GetData();    //擷取一個AggregateCacheDependency對象,UserTableDependency儲存的是表    AggregateCacheDependency cd = new TableDependency("UserTableDependency").GetDependency();    //添加到緩衝    HttpRuntime.Cache.Add(cacheKey, data, cd, DateTime.Now.AddHours(10), Cache.NoSlidingExpiration, CacheItemPriority.High, null);}Response.Write(data);

 

 

 

聯繫我們

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